Compare commits
91
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
274ce28e8d
|
||
|
|
1fcecdb04d
|
||
|
|
e456bb8d7a
|
||
|
|
202c785f94
|
||
|
|
7629a73e0a
|
||
|
|
ce2e3e4cd3
|
||
|
|
3320f222bb
|
||
|
|
099857b636
|
||
|
|
20adc196d9 | ||
|
|
ae891262e1
|
||
|
|
6f45f4f205 | ||
|
|
65d2d40310
|
||
|
|
fa21a029ae | ||
|
|
12e2a4edcc
|
||
|
|
78d10cf03c | ||
|
|
5d3d48e802
|
||
|
|
331ad752d1 | ||
|
|
9458312d73
|
||
|
|
4b72b2a0dd | ||
|
|
c2112f6ee1
|
||
|
|
9896e7c657 | ||
|
|
4574aa17c3
|
||
|
|
bb010d565e | ||
|
|
e809ce63d3
|
||
|
|
59c0d0c3b4 | ||
|
|
79a682b8ec
|
||
|
|
d0b91f8526 | ||
|
|
2b881f5a76
|
||
|
|
4d8dcf28bb | ||
|
|
d7c2ec880f
|
||
|
|
c248b91147 | ||
|
|
46bd0c42d3
|
||
|
|
c6ef56114f | ||
|
|
701f5b0339
|
||
|
|
cc4cb23b76
|
||
|
|
f42c83bdca
|
||
|
|
cf14039077
|
||
|
|
1f1a92d43f
|
||
|
|
38790c0b45
|
||
|
|
5f6bd408a4
|
||
|
|
a77dce1c56 | ||
|
|
b9a32e460a
|
||
|
|
e8079b67fb
|
||
|
|
bde999f1fe
|
||
|
|
26c69d5660
|
||
|
|
ffd2975484 | ||
|
|
a62ddb0f74
|
||
|
|
79e4a64ff2
|
||
|
|
3ca58dcc24
|
||
|
|
bb8669bf46
|
||
|
|
6205b82e0b
|
||
|
|
088101449a
|
||
|
|
b1e75973f9
|
||
|
|
3ee0da3c0a
|
||
|
|
29f46c6606 | ||
|
|
30e3e4145a
|
||
|
|
4233b90b82
|
||
|
|
da00e9c50c
|
||
|
|
fee89d7522
|
||
|
|
bc95b33bd9
|
||
|
|
6cd24bf14f
|
||
|
|
b86cf0117d | ||
|
|
6fdb4828c3
|
||
|
|
44f03f771b
|
||
|
|
ba3af3c01b
|
||
|
|
66c1b1a033
|
||
|
|
f8b9c5b27d
|
||
|
|
e99bb58453
|
||
|
|
db0b71c9ad
|
||
|
|
35b65bb524
|
||
|
|
6e594c15d7
|
||
|
|
d58a96a4c4 | ||
|
|
725c28b3f5
|
||
|
|
d8db99eb81
|
||
|
|
63215ac02f
|
||
|
|
e7647165bc
|
||
|
|
f32a25eb59
|
||
|
|
d680504c31
|
||
|
|
aeea8ca900
|
||
|
|
05dd37a30a
|
||
|
|
f700e400d5
|
||
|
|
2b25364252
|
||
|
|
917b0e1b9a
|
||
|
|
ad2ae00f39
|
||
|
|
fa089c5cd0 | ||
|
|
ae1ba0d2d3
|
||
|
|
ffa41db994
|
||
|
|
13425cee03
|
||
|
|
fae4e9a9fd
|
||
|
|
340442d374
|
||
|
|
013ca4355c
|
+32
-4
@@ -1,7 +1,35 @@
|
|||||||
{"type":"meta","next_id":{"DSC":39,"AGD":42,"DEC":38,"PLN":87,"LSN":53,"CLSN":1}}
|
{"type":"meta","next_id":{"DSC":67,"AGD":70,"DEC":59,"PLN":138,"LSN":75,"CLSN":1}}
|
||||||
{"type":"discussion","id":"DSC-0038","status":"open","ticket":"studio-packer-rgba8888-asset-pipeline","title":"Studio and Packer RGBA8888 Asset Pipeline Alignment","created_at":"2026-05-23","updated_at":"2026-05-23","tags":["studio","packer","assets","glyph-bank","palette","rgba8888","runtime-alignment"],"agendas":[{"id":"AGD-0041","file":"AGD-0041-studio-packer-rgba8888-asset-pipeline.md","status":"accepted","created_at":"2026-05-23","updated_at":"2026-05-23"}],"decisions":[{"id":"DEC-0037","file":"DEC-0037-studio-packer-rgba8888-asset-pipeline.md","status":"accepted","created_at":"2026-05-23","updated_at":"2026-05-23","ref_agenda":"AGD-0041"}],"plans":[{"id":"PLN-0081","file":"PLN-0081-rgba8888-packer-and-studio-spec-propagation.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23","ref_decisions":["DEC-0037"]},{"id":"PLN-0082","file":"PLN-0082-rgba8888-palette-model-and-argb-conversion.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23","ref_decisions":["DEC-0037"]},{"id":"PLN-0083","file":"PLN-0083-rgba8888-glyph-payload-emission-and-sizes.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23","ref_decisions":["DEC-0037"]},{"id":"PLN-0084","file":"PLN-0084-rgba8888-packer-projections-and-workspace-apis.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23","ref_decisions":["DEC-0037"]},{"id":"PLN-0085","file":"PLN-0085-rgba8888-tests-fixtures-and-conformance.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23","ref_decisions":["DEC-0037"]},{"id":"PLN-0086","file":"PLN-0086-rgba8888-final-integration-and-residue-removal.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23","ref_decisions":["DEC-0037"]}],"lessons":[]}
|
{"type":"discussion","id":"DSC-0066","status":"done","ticket":"pbs-lsp-remaining-editor-surface","title":"PBS LSP Remaining Editor Surface","created_at":"2026-09-22","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0074","file":"discussion/lessons/DSC-0066-pbs-lsp-remaining-editor-surface/LSN-0074-pbs-remaining-editor-surface-is-frontend-owned.md","status":"done","created_at":"2026-09-22","updated_at":"2026-09-22"}]}
|
||||||
|
{"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"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0062","status":"done","ticket":"multi-frontend-pvm-neutrality","title":"Neutralidade da PVM e identificacao PBX independente de PBS","created_at":"2026-07-15","updated_at":"2026-09-18","tags":["vm-arch","runtime","pvm","pbx","compiler","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0061","file":"discussion/lessons/DSC-0062-multi-frontend-pvm-neutrality/LSN-0061-pbx-runtime-boundary.md","status":"done","created_at":"2026-09-18","updated_at":"2026-09-18"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0061","status":"done","ticket":"multi-frontend-sdk-canonical-definition","title":"Auditoria e centralizacao gradual da definicao canonica do SDK","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","sdk","stdlib","hostcalls","intrinsics","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0064","file":"discussion/lessons/DSC-0061-multi-frontend-sdk-canonical-definition/LSN-0064-runtime-owns-console-abi-pbs-is-delivery.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0060","status":"done","ticket":"multi-frontend-validation-boundaries","title":"Separar validacoes de linguagem e validacoes de plataforma","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","compiler-pbs","backend","validation","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0063","file":"discussion/lessons/DSC-0060-multi-frontend-validation-boundaries/LSN-0063-language-vs-platform-validation-ownership.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0059","status":"done","ticket":"multi-frontend-common-lifecycle","title":"Extrair lifecycle comum das responsabilidades do frontend PBS","created_at":"2026-07-15","updated_at":"2026-09-19","tags":["compiler","compiler-general","compiler-pbs","lifecycle","backend","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0062","file":"discussion/lessons/DSC-0059-multi-frontend-common-lifecycle/LSN-0062-common-lifecycle-assembly-stage.md","status":"done","created_at":"2026-09-19","updated_at":"2026-09-19"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0058","status":"done","ticket":"multi-frontend-serializable-ir","title":"Manter a IR comum serializavel por design","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","ir","backend","serialization","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0060","file":"discussion/lessons/DSC-0058-multi-frontend-serializable-ir/LSN-0060-data-contract-first-for-serializable-irbackend.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0057","status":"done","ticket":"multi-frontend-frontend-backend-contract","title":"Estabilizar contrato entre frontend e backend comum","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","compiler-pbs","ir","backend","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0059","file":"discussion/lessons/DSC-0057-multi-frontend-frontend-backend-contract/LSN-0059-common-irbackend-handoff-and-backend-guardrails.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0056","status":"done","ticket":"multi-frontend-remove-pbs-branches","title":"Generalizar o contrato LSP/editorial para frontends","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","compiler-pbs","studio","frontend","coupling","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0058","file":"discussion/lessons/DSC-0056-multi-frontend-remove-pbs-branches/LSN-0058-generic-frontend-editorial-contract-for-lsp.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0055","status":"done","ticket":"multi-frontend-compiler-vs-language-services","title":"Separar compilacao de servicos editoriais de frontend","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","studio","lsp","editor","frontend","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0056","file":"discussion/lessons/DSC-0055-multi-frontend-compiler-vs-language-services/LSN-0056-compile-first-frontends-with-optional-editorial-capabilities.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0054","status":"done","ticket":"multi-frontend-provider-contract","title":"Introduzir provider completo de frontend","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["compiler","compiler-general","studio","frontend","registry","multi-frontend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0055","file":"discussion/lessons/DSC-0054-multi-frontend-provider-contract/LSN-0055-static-frontend-providers-before-plugin-architecture.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0053","status":"done","ticket":"pbs-lsp-call-and-type-hierarchy","title":"PBS LSP Call and Type Hierarchy","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","call-hierarchy","type-hierarchy"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0052","status":"done","ticket":"pbs-lsp-document-links","title":"PBS LSP Document Links","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","document-links","imports"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0051","status":"done","ticket":"pbs-lsp-diagnostics-ux","title":"PBS LSP Diagnostics UX","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","diagnostics","ux"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0050","status":"done","ticket":"pbs-lsp-folding-and-selection-ranges","title":"PBS LSP Folding and Selection Ranges","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","folding","selection-range"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0049","status":"done","ticket":"pbs-lsp-completion-depth","title":"PBS LSP Completion Depth","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","completion"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0048","status":"done","ticket":"pbs-lsp-performance-cache-and-snapshots","title":"PBS LSP Performance Cache and Snapshots","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","performance","caching"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0047","status":"done","ticket":"pbs-lsp-semantic-tokens-semantic-classification","title":"PBS LSP Semantic Token Classification","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","semantic-tokens"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0046","status":"done","ticket":"pbs-lsp-import-assistance","title":"PBS LSP Import Assistance","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","imports","completion"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0045","status":"done","ticket":"pbs-lsp-formatting","title":"PBS LSP Formatting","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","formatting"],"agendas":[],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0044","status":"done","ticket":"pbs-lsp-code-actions","title":"PBS LSP Code Actions and Quick Fixes","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","code-actions","quick-fix"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0073","file":"discussion/lessons/DSC-0044-pbs-lsp-code-actions/LSN-0073-pbs-quick-fixes-are-frontend-repairs-transported-by-the-lsp.md","status":"done","created_at":"2026-09-22","updated_at":"2026-09-22"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0043","status":"done","ticket":"pbs-lsp-rename-symbol","title":"PBS LSP Rename Symbol","created_at":"2026-07-15","updated_at":"2026-09-22","tags":["studio","lsp","vscode","compiler-pbs","editor","rename"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0072","file":"discussion/lessons/DSC-0043-pbs-lsp-rename-symbol/LSN-0072-pbs-rename-is-a-validated-physical-workspace-edit.md","status":"done","created_at":"2026-09-22","updated_at":"2026-09-22"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0042","status":"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"}]}
|
||||||
{"type":"discussion","id":"DSC-0037","status":"done","ticket":"pbs-autocomplete-parameter-names","title":"PBS autocomplete parameter names for stdlib and method calls","created_at":"2026-05-08","updated_at":"2026-05-14","tags":["compiler-pbs","studio","lsp","autocomplete","signature-help","stdlib"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0052","file":"discussion/lessons/DSC-0037-pbs-autocomplete-parameter-names/LSN-0052-canonical-callable-parameter-names-through-pbs-editor-assistance.md","status":"done","created_at":"2026-05-14","updated_at":"2026-05-14"}]}
|
{"type":"discussion","id":"DSC-0037","status":"done","ticket":"pbs-autocomplete-parameter-names","title":"PBS autocomplete parameter names for stdlib and method calls","created_at":"2026-05-08","updated_at":"2026-05-14","tags":["compiler-pbs","studio","lsp","autocomplete","signature-help","stdlib"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0052","file":"discussion/lessons/DSC-0037-pbs-autocomplete-parameter-names/LSN-0052-canonical-callable-parameter-names-through-pbs-editor-assistance.md","status":"done","created_at":"2026-05-14","updated_at":"2026-05-14"}]}
|
||||||
{"type":"discussion","id":"DSC-0036","status":"open","ticket":"pbs-symbol-documentation-and-hover-markdown","title":"Modelo de documentacao de simbolos em PBS e consumo markdown no hover","created_at":"2026-05-08","updated_at":"2026-05-08","tags":["compiler","compiler-pbs","studio","lsp","vscode","editor","hover","documentation","markdown"],"agendas":[{"id":"AGD-0039","file":"AGD-0039-pbs-symbol-documentation-and-hover-markdown.md","status":"open","created_at":"2026-05-08","updated_at":"2026-05-08"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0036","status":"done","ticket":"pbs-symbol-documentation-and-hover-markdown","title":"Modelo de documentacao de simbolos em PBS e consumo markdown no hover","created_at":"2026-05-08","updated_at":"2026-07-15","tags":["compiler","compiler-pbs","studio","lsp","vscode","editor","hover","documentation","markdown"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0057","file":"discussion/lessons/DSC-0036-pbs-symbol-documentation-and-hover-markdown/LSN-0057-compiler-owned-pbs-doc-markdown-for-editor-assistance.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
|
||||||
{"type":"discussion","id":"DSC-0035","status":"done","ticket":"pbs-lsp-editor-assistance-wave-1","title":"Wave 1 de assistencia editorial via LSP para PBS no VS Code","created_at":"2026-05-08","updated_at":"2026-05-08","tags":["studio","lsp","vscode","compiler","compiler-pbs","editor","completion","hover","signature-help"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0051","file":"discussion/lessons/DSC-0035-pbs-lsp-editor-assistance-wave-1/LSN-0051-compiler-backed-editor-assistance-for-pbs.md","status":"done","created_at":"2026-05-08","updated_at":"2026-05-08"}]}
|
{"type":"discussion","id":"DSC-0035","status":"done","ticket":"pbs-lsp-editor-assistance-wave-1","title":"Wave 1 de assistencia editorial via LSP para PBS no VS Code","created_at":"2026-05-08","updated_at":"2026-05-08","tags":["studio","lsp","vscode","compiler","compiler-pbs","editor","completion","hover","signature-help"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0051","file":"discussion/lessons/DSC-0035-pbs-lsp-editor-assistance-wave-1/LSN-0051-compiler-backed-editor-assistance-for-pbs.md","status":"done","created_at":"2026-05-08","updated_at":"2026-05-08"}]}
|
||||||
{"type":"discussion","id":"DSC-0034","status":"done","ticket":"frontend-semantic-host-projection-flexibility","title":"Frontend semantic vocabulary flexibility and declarative host projection","created_at":"2026-05-06","updated_at":"2026-05-07","tags":["compiler","compiler-general","frontend","semantics","vscode","host-projection","lsp"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0048","file":"discussion/lessons/DSC-0034-frontend-semantic-host-projection-flexibility/LSN-0048-frontend-owned-semantic-vocabularies-with-declarative-host-projection.md","status":"done","created_at":"2026-05-07","updated_at":"2026-05-07"}]}
|
{"type":"discussion","id":"DSC-0034","status":"done","ticket":"frontend-semantic-host-projection-flexibility","title":"Frontend semantic vocabulary flexibility and declarative host projection","created_at":"2026-05-06","updated_at":"2026-05-07","tags":["compiler","compiler-general","frontend","semantics","vscode","host-projection","lsp"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0048","file":"discussion/lessons/DSC-0034-frontend-semantic-host-projection-flexibility/LSN-0048-frontend-owned-semantic-vocabularies-with-declarative-host-projection.md","status":"done","created_at":"2026-05-07","updated_at":"2026-05-07"}]}
|
||||||
{"type":"discussion","id":"DSC-0033","status":"done","ticket":"frontend-visual-theme-spec-and-css-retirement","title":"Frontend visual theme spec and retirement of host-consumed semantic CSS","created_at":"2026-05-06","updated_at":"2026-05-08","tags":["compiler","compiler-general","frontend","presentation","theming","studio","vscode","lsp","pbs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0050","file":"discussion/lessons/DSC-0033-frontend-visual-theme-spec-and-css-retirement/LSN-0050-frontend-owned-visual-themes-with-structured-contract-and-host-adapters.md","status":"done","created_at":"2026-05-08","updated_at":"2026-05-08"}]}
|
{"type":"discussion","id":"DSC-0033","status":"done","ticket":"frontend-visual-theme-spec-and-css-retirement","title":"Frontend visual theme spec and retirement of host-consumed semantic CSS","created_at":"2026-05-06","updated_at":"2026-05-08","tags":["compiler","compiler-general","frontend","presentation","theming","studio","vscode","lsp","pbs"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0050","file":"discussion/lessons/DSC-0033-frontend-visual-theme-spec-and-css-retirement/LSN-0050-frontend-owned-visual-themes-with-structured-contract-and-host-adapters.md","status":"done","created_at":"2026-05-08","updated_at":"2026-05-08"}]}
|
||||||
@@ -18,7 +46,7 @@
|
|||||||
{"type":"discussion","id":"DSC-0002","status":"done","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-04-23","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0002-palette-management-in-studio/LSN-0042-schema-driven-palette-authoring-and-local-metadata-events.md","status":"done","created_at":"2026-04-23","updated_at":"2026-04-23"}]}
|
{"type":"discussion","id":"DSC-0002","status":"done","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-04-23","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0002-palette-management-in-studio/LSN-0042-schema-driven-palette-authoring-and-local-metadata-events.md","status":"done","created_at":"2026-04-23","updated_at":"2026-04-23"}]}
|
||||||
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
|
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
|
||||||
{"type":"discussion","id":"DSC-0004","status":"abandoned","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-04-24","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"abandoned","created_at":"2026-03-26","updated_at":"2026-04-24","_override_reason":"Explicit user request on 2026-04-24 to abandon AGD-0004 because the agenda is no longer valid."}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0004","status":"abandoned","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-04-24","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"abandoned","created_at":"2026-03-26","updated_at":"2026-04-24","_override_reason":"Explicit user request on 2026-04-24 to abandon AGD-0004 because the agenda is no longer valid."}],"decisions":[],"plans":[],"lessons":[]}
|
||||||
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0005","status":"done","ticket":"variable-tile-bank-palette-serialization","title":"Variable Glyph Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-07-14","tags":["packer","legacy-import","glyph-bank","palette-serialization","rgba8888","runtime-alignment"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0054","file":"discussion/lessons/DSC-0005-variable-glyph-bank-palette-serialization/LSN-0054-runtime-owned-variable-glyph-palette-counts.md","status":"done","created_at":"2026-07-14","updated_at":"2026-07-14"}]}
|
||||||
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
|
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
|
||||||
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
|
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
|
||||||
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
|
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
|
||||||
|
|||||||
+126
@@ -0,0 +1,126 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0054
|
||||||
|
ticket: variable-tile-bank-palette-serialization
|
||||||
|
title: Runtime-Owned Variable Glyph Palette Counts
|
||||||
|
created: 2026-07-14
|
||||||
|
tags:
|
||||||
|
- packer
|
||||||
|
- studio
|
||||||
|
- glyph-bank
|
||||||
|
- palette-serialization
|
||||||
|
- rgba8888
|
||||||
|
- runtime-alignment
|
||||||
|
---
|
||||||
|
|
||||||
|
# Runtime-Owned Variable Glyph Palette Counts
|
||||||
|
|
||||||
|
### Original Problem
|
||||||
|
|
||||||
|
The first RGBA8888 alignment wave made Studio and packer emit palette colors in
|
||||||
|
the runtime channel order, but it deliberately kept the old fixed glyph-bank
|
||||||
|
palette payload shape. Every `GLYPH/indexed_v1` payload still reserved room for
|
||||||
|
64 palettes, so the emitted palette block was always `64 * 16 * 4 = 4096`
|
||||||
|
bytes even when the bank used one or a few palettes.
|
||||||
|
|
||||||
|
That fixed shape left two problems:
|
||||||
|
|
||||||
|
- packer output was larger than the runtime needed;
|
||||||
|
- `palette_count` could not be trusted as the effective runtime resident count,
|
||||||
|
because the payload still looked like a 64-palette bank.
|
||||||
|
|
||||||
|
Runtime later accepted the variable-palette protocol for
|
||||||
|
`GLYPH/indexed_v1`. Studio and packer had to follow that runtime-owned wire
|
||||||
|
contract instead of keeping a stale producer-side convention.
|
||||||
|
|
||||||
|
### Consolidated Decision
|
||||||
|
|
||||||
|
Runtime owns the `GLYPH/indexed_v1` protocol. Studio and packer are downstream
|
||||||
|
producers of runtime-conforming `assets.pa` payloads.
|
||||||
|
|
||||||
|
The accepted rule is:
|
||||||
|
|
||||||
|
1. `palette_count` is the effective serialized and resident palette count.
|
||||||
|
2. `palette_count` must be in the inclusive range `1..=64`.
|
||||||
|
3. Palette bytes are exactly `palette_count * 16 * 4`.
|
||||||
|
4. `size = ceil(width * height / 2) + palette_count * 16 * 4`.
|
||||||
|
5. `decoded_size = width * height + palette_count * 16 * 4`.
|
||||||
|
6. Palette bytes remain RGBA8888 in `R`, `G`, `B`, `A` order.
|
||||||
|
7. `GLYPH/indexed_v1` remains the format name. This change does not introduce
|
||||||
|
`GLYPH/indexed_v2`.
|
||||||
|
8. There is no compatibility mode for the old fixed 64-palette padding.
|
||||||
|
9. Palette IDs remain direct. There is no sparse-to-dense remapping metadata in
|
||||||
|
v1.
|
||||||
|
10. `palette_authored`, when present, is informative tooling metadata only.
|
||||||
|
|
||||||
|
### Implementation Result
|
||||||
|
|
||||||
|
The packer specs now define `palette_count` as runtime-effective metadata for
|
||||||
|
glyph banks and describe the variable palette payload in the build-artifact
|
||||||
|
contract. Studio-facing asset workspace docs now keep `palette_count` distinct
|
||||||
|
from any authored or tooling-only palette count.
|
||||||
|
|
||||||
|
The packer metadata model derives and validates effective palette count instead
|
||||||
|
of hard-coding `64`. Sparse direct palette IDs are preserved by materializing
|
||||||
|
intermediate palette slots up to the highest referenced ID; those slots are not
|
||||||
|
a remapping table.
|
||||||
|
|
||||||
|
Payload emission now writes exactly the effective number of palette slots. Size
|
||||||
|
and decoded-size accounting use the same formula as the runtime contract, so
|
||||||
|
metadata, asset-table entries, and payload lengths agree.
|
||||||
|
|
||||||
|
Tests and fixtures cover `palette_count = 1`, intermediate counts, `64`, sparse
|
||||||
|
direct identity, invalid counts above `64`, RGBA8888 byte order, and payload
|
||||||
|
size accounting. Final validation passed with:
|
||||||
|
|
||||||
|
- `discussion validate`;
|
||||||
|
- `./gradlew :prometeu-packer:prometeu-packer-v1:test`;
|
||||||
|
- `./gradlew build`.
|
||||||
|
|
||||||
|
### Practical Examples
|
||||||
|
|
||||||
|
A 256 by 256 glyph bank with one palette has:
|
||||||
|
|
||||||
|
```text
|
||||||
|
pixel bytes = ceil(256 * 256 / 2) = 32768
|
||||||
|
palette bytes = 1 * 16 * 4 = 64
|
||||||
|
size = 32768 + 64 = 32832
|
||||||
|
decoded_size = 256 * 256 + 64 = 65600
|
||||||
|
```
|
||||||
|
|
||||||
|
A bank that references palette ID `6` has an effective `palette_count` of at
|
||||||
|
least `7`. Palette slots `0` through `6` exist in the serialized palette block.
|
||||||
|
If some lower slots were not authored directly, they are deterministic
|
||||||
|
placeholders; palette `6` is not remapped to palette `0`.
|
||||||
|
|
||||||
|
### Common Pitfalls and Anti-patterns
|
||||||
|
|
||||||
|
- Do not infer runtime payload length from the maximum allowed palette count.
|
||||||
|
`64` is the upper bound, not the default emitted count.
|
||||||
|
- Do not use `palette_authored` as a runtime-effective field. It may describe a
|
||||||
|
tool view, but runtime loads `palette_count`.
|
||||||
|
- Do not preserve fixed 4096-byte palette padding for banks with fewer than 64
|
||||||
|
effective palettes.
|
||||||
|
- Do not create `GLYPH/indexed_v2` to carry this change. The accepted runtime
|
||||||
|
protocol keeps the v1 format name.
|
||||||
|
- Do not introduce sparse-to-dense palette remapping metadata. Existing scene,
|
||||||
|
sprite, packer, and runtime references use direct palette identity.
|
||||||
|
- Do not combine RGBA8888 channel-order work with palette-count semantics.
|
||||||
|
RGBA8888 defines each color value; `palette_count` defines how many palettes
|
||||||
|
are serialized and resident.
|
||||||
|
|
||||||
|
### References
|
||||||
|
|
||||||
|
- Runtime decision:
|
||||||
|
`../runtime/discussion/workflow/decisions/DEC-0041-variable-glyph-bank-palette-protocol.md`.
|
||||||
|
- Studio/packer decision:
|
||||||
|
`discussion/workflow/decisions/DEC-0038-variable-glyph-bank-palette-serialization.md`.
|
||||||
|
- `PLN-0087`: Variable glyph palette spec propagation.
|
||||||
|
- `PLN-0088`: Variable glyph palette metadata and count model.
|
||||||
|
- `PLN-0089`: Variable glyph palette payload emission and size accounting.
|
||||||
|
- `PLN-0090`: Studio and packer projections for variable glyph palettes.
|
||||||
|
- `PLN-0091`: Variable glyph palette tests, fixtures, and final validation.
|
||||||
|
- Prior lesson:
|
||||||
|
`discussion/lessons/DSC-0038-studio-packer-rgba8888-asset-pipeline/LSN-0053-rgba8888-is-the-canonical-studio-packer-palette-contract.md`.
|
||||||
|
- `docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md`.
|
||||||
|
- `docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md`.
|
||||||
|
- `docs/specs/studio/4. Assets Workspace Specification.md`.
|
||||||
+104
@@ -0,0 +1,104 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0057
|
||||||
|
ticket: pbs-symbol-documentation-and-hover-markdown
|
||||||
|
title: Compiler-Owned PBS Doc Markdown for Editor Assistance
|
||||||
|
created: 2026-07-15
|
||||||
|
tags: [compiler, compiler-pbs, studio, lsp, vscode, editor, hover, documentation, markdown]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS editor assistance had compiler-backed completion, hover, and signature-help surfaces, but it did not yet have a canonical authored documentation model for named API symbols.
|
||||||
|
|
||||||
|
Without that model, hover could show mechanical facts such as kind, signature, origin, and type shape, but it could not reliably explain intent, parameter meaning, semantic constraints, or usage notes. Any editor-side solution would have risked reparsing PBS source or inventing a second documentation binding model outside the compiler.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS symbol documentation is authored with a reserved compiler-recognized `Doc` attribute:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
[Doc(markdown = """
|
||||||
|
Draws a sprite.
|
||||||
|
|
||||||
|
- `x`: screen x coordinate
|
||||||
|
- `y`: screen y coordinate
|
||||||
|
""")]
|
||||||
|
```
|
||||||
|
|
||||||
|
The v1 shape is intentionally narrow:
|
||||||
|
|
||||||
|
1. `Doc` has exactly one required named argument, `markdown`.
|
||||||
|
2. The `markdown` argument uses a triple-quoted documentation text block.
|
||||||
|
3. The text block is documentation-only metadata, not a general runtime multiline string literal.
|
||||||
|
4. `[Doc]` attaches to the following declaration using the normal PBS attribute association rule.
|
||||||
|
5. Attribute order is semantically irrelevant.
|
||||||
|
6. Parameters do not receive `[Doc]` in v1; parameter notes live inside the owning declaration's Markdown.
|
||||||
|
7. Duplicate `Doc`, missing `markdown`, extra arguments, aliases, positional arguments, empty normalized payloads, and invalid targets are semantic errors.
|
||||||
|
|
||||||
|
The compiler owns documentation resolution. LSP and editor consumers receive normalized compiler metadata; they must not reparse PBS source to discover documentation.
|
||||||
|
|
||||||
|
## Final Implementation Shape
|
||||||
|
|
||||||
|
The work landed as a staged compiler-to-editor pipeline:
|
||||||
|
|
||||||
|
1. PBS specs define the syntax, static semantics, AST shape, diagnostics, and stdlib documentation policy for `[Doc(markdown = """...""")]`.
|
||||||
|
2. The PBS lexer recognizes triple-quoted documentation text blocks without changing ordinary string literal behavior.
|
||||||
|
3. The parser and AST preserve documentation text block payloads and spans as structured attribute values.
|
||||||
|
4. A shared normalizer removes incidental surrounding blank lines and common indentation while preserving Markdown content and internal line breaks.
|
||||||
|
5. Semantic validation reserves `Doc` and enforces the single canonical v1 shape.
|
||||||
|
6. Normalized Markdown is attached to resolved PBS semantic symbols as structured documentation metadata.
|
||||||
|
7. PBS editorial and LSP surfaces transport that metadata without source reparsing.
|
||||||
|
8. Hover composition includes the normalized Markdown while preserving existing fallback behavior for undocumented symbols.
|
||||||
|
9. Stdlib, SDK, and interface declarations use the same authored documentation surface.
|
||||||
|
10. Runtime-facing artifacts remain unchanged by documentation metadata.
|
||||||
|
|
||||||
|
This preserves a clean boundary: PBS source authors write documentation in the language, the compiler resolves it, LSP transports it, and editors render it.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Valid documentation belongs on named API declarations that introduce semantic symbols and can carry attributes, such as functions, methods, services, hosts, interface declarations, and repository-owned stdlib or SDK declarations.
|
||||||
|
|
||||||
|
Parameter documentation is written inside the callable's Markdown:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
[Doc(markdown = """
|
||||||
|
Fills a rectangle.
|
||||||
|
|
||||||
|
- `x`: left edge in screen coordinates
|
||||||
|
- `y`: top edge in screen coordinates
|
||||||
|
- `width`: rectangle width in pixels
|
||||||
|
- `height`: rectangle height in pixels
|
||||||
|
""")]
|
||||||
|
```
|
||||||
|
|
||||||
|
Invalid v1 forms include:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
[Doc("Draws a sprite.")]
|
||||||
|
[Doc(text = """Draws a sprite.""")]
|
||||||
|
[Doc(markdown = """Draws a sprite.""", format = "markdown")]
|
||||||
|
[Documentation(markdown = """Draws a sprite.""")]
|
||||||
|
```
|
||||||
|
|
||||||
|
These are rejected because accepting aliases or positional shortcuts would immediately expand the language contract and make future compatibility harder.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not treat `"""..."""` as a general PBS runtime string literal. Runtime multiline strings raise separate questions about type behavior, lowering, constant pools, equality, escaping, and artifact representation.
|
||||||
|
|
||||||
|
Do not let LSP or editor code rediscover documentation by scanning source. That duplicates language semantics outside the compiler and breaks as soon as imports, stdlib declarations, interface modules, or generated sources participate.
|
||||||
|
|
||||||
|
Do not attach `[Doc]` to parameters in v1. Parameter docs are authored inside the declaration Markdown so the compiler can keep one documentation payload per API symbol.
|
||||||
|
|
||||||
|
Do not reflow authored Markdown in a formatter or hover composer. The normalizer may remove incidental indentation, but it must preserve the author's Markdown content.
|
||||||
|
|
||||||
|
Do not lower documentation into runtime artifacts by default. Documentation is compile/editor metadata unless a future runtime or packaging decision explicitly changes that boundary.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- `DEC-0039` captured the normative decision for PBS `Doc` markdown text blocks.
|
||||||
|
- `PLN-0092` specified the PBS docs and diagnostics contract.
|
||||||
|
- `PLN-0093` through `PLN-0099` implemented lexer, parser, normalization, semantics, symbol metadata, LSP exposure, and hover composition.
|
||||||
|
- `PLN-0100` authored stdlib, SDK, and interface documentation.
|
||||||
|
- `PLN-0101` protected runtime artifacts from documentation lowering.
|
||||||
|
- `PLN-0102` closed end-to-end conformance coverage.
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0053
|
||||||
|
ticket: studio-packer-rgba8888-asset-pipeline
|
||||||
|
title: RGBA8888 Is the Canonical Studio and Packer Palette Contract
|
||||||
|
created: 2026-07-14
|
||||||
|
tags:
|
||||||
|
- studio
|
||||||
|
- packer
|
||||||
|
- assets
|
||||||
|
- glyph-bank
|
||||||
|
- palette
|
||||||
|
- rgba8888
|
||||||
|
- runtime-alignment
|
||||||
|
---
|
||||||
|
|
||||||
|
# RGBA8888 Is the Canonical Studio and Packer Palette Contract
|
||||||
|
|
||||||
|
### Original Problem
|
||||||
|
|
||||||
|
The runtime moved to RGBA8888 as the canonical logical color and framebuffer
|
||||||
|
format, but Studio and packer still treated glyph-bank palettes as RGB565-era
|
||||||
|
data. The old pipeline exposed `convertedRgb565`, preserved ARGB as normal
|
||||||
|
projected metadata, reserved palette index `0` for transparency, flattened or
|
||||||
|
discarded alpha semantics, and carried magenta color-key behavior as a hidden
|
||||||
|
transparency shortcut.
|
||||||
|
|
||||||
|
That made the asset pipeline ambiguous. A glyph-bank asset could look valid to
|
||||||
|
Studio while still carrying palette data that no longer matched the runtime
|
||||||
|
contract.
|
||||||
|
|
||||||
|
### Consolidated Decision
|
||||||
|
|
||||||
|
`GLYPH/indexed_v1` remains the runtime-facing format name and keeps its
|
||||||
|
indexed/paletized glyph-bank identity. The incompatible change is inside the
|
||||||
|
palette contract:
|
||||||
|
|
||||||
|
1. `rgba8888` is the canonical authored, projected, and emitted palette field.
|
||||||
|
2. RGBA8888 values are interpreted as `0xRRGGBBAA` in runtime channel order.
|
||||||
|
3. Java `BufferedImage` ARGB values are input-only host API details and must be
|
||||||
|
converted deliberately at the packer boundary.
|
||||||
|
4. Palette index `0` is ordinary. Glyph palettes have 16 usable entries.
|
||||||
|
5. Transparency, including partial transparency, is represented only by alpha.
|
||||||
|
6. Magenta color-key behavior is not a normal Studio or packer feature.
|
||||||
|
7. RGB565 is not a compatibility path for runtime-facing glyph-bank palettes.
|
||||||
|
|
||||||
|
### Implementation Result
|
||||||
|
|
||||||
|
The packer specs now define glyph-bank palette metadata with `rgba8888`, and
|
||||||
|
the binary `GLYPH/indexed_v1` payload uses a `64 * 16 * 4 = 4096` byte palette
|
||||||
|
block instead of the old `64 * 16 * 2 = 2048` byte RGB565 block.
|
||||||
|
|
||||||
|
The packer palette model now carries canonical RGBA8888 values. Image import
|
||||||
|
converts Java ARGB pixels into runtime RGBA values before palette extraction,
|
||||||
|
and palette identity includes alpha. This allows transparent and partially
|
||||||
|
transparent colors to be distinct palette entries.
|
||||||
|
|
||||||
|
Packer read, detail, write, and cache paths now use `rgba8888` as the normal
|
||||||
|
metadata contract. Emission writes palette bytes in `R`, `G`, `B`, `A` order
|
||||||
|
and no longer emits a synthetic magenta entry for index `0`.
|
||||||
|
|
||||||
|
Tests and fixtures were updated to prove the new contract: RGBA channel order,
|
||||||
|
alpha preservation, 16 usable colors, index `0` as ordinary data, magenta as
|
||||||
|
ordinary color data, and 4096-byte palette blocks. Final validation confirmed
|
||||||
|
that remaining stale-looking references are either normative "not supported"
|
||||||
|
statements, historical discussion context, or explicitly out-of-scope generated
|
||||||
|
project cache data.
|
||||||
|
|
||||||
|
### Practical Pattern
|
||||||
|
|
||||||
|
When a host API exposes color in a different layout than the runtime contract,
|
||||||
|
name the boundary explicitly and keep the canonical field runtime-oriented.
|
||||||
|
For this pipeline:
|
||||||
|
|
||||||
|
- accept host ARGB only at import/read time;
|
||||||
|
- convert to RGBA8888 before storing palette metadata;
|
||||||
|
- project `rgba8888` to Studio and packer clients;
|
||||||
|
- emit RGBA bytes directly into `assets.pa`;
|
||||||
|
- convert back to UI-friendly ARGB only inside presentation code.
|
||||||
|
|
||||||
|
This keeps tooling convenient without letting host representation leak into the
|
||||||
|
runtime asset contract.
|
||||||
|
|
||||||
|
### Common Pitfalls and Anti-patterns
|
||||||
|
|
||||||
|
- Do not treat `originalArgb8888` as canonical pipeline data. ARGB can be a UI
|
||||||
|
or image-input representation, but `rgba8888` owns the contract.
|
||||||
|
- Do not reintroduce `convertedRgb565` as a normal projected field or emitted
|
||||||
|
payload. RGB565 compatibility was deliberately rejected for this path.
|
||||||
|
- Do not reserve palette index `0` for transparency. Alpha owns transparency.
|
||||||
|
- Do not use magenta as a hidden color key. A magenta RGBA value is just color
|
||||||
|
data unless an explicit future import tool defines a separate conversion.
|
||||||
|
- Do not change scene `palette_id` semantics as part of color-format work.
|
||||||
|
Scene records still reference glyph-bank palette indices.
|
||||||
|
- Do not fold `DSC-0005` variable palette-count work into RGBA8888 cleanup.
|
||||||
|
Palette encoding changed here; palette-count optimization remains separate.
|
||||||
|
|
||||||
|
### References
|
||||||
|
|
||||||
|
- `DEC-0037`: Studio and Packer RGBA8888 Asset Pipeline Contract.
|
||||||
|
- `PLN-0081`: Packer and Studio spec propagation.
|
||||||
|
- `PLN-0082`: Palette model and ARGB conversion boundary.
|
||||||
|
- `PLN-0083`: Glyph payload emission and size accounting.
|
||||||
|
- `PLN-0084`: Packer projections and workspace APIs.
|
||||||
|
- `PLN-0085`: Tests, fixtures, and conformance updates.
|
||||||
|
- `PLN-0086`: Final integration and residue removal.
|
||||||
|
- `docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md`.
|
||||||
|
- `docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md`.
|
||||||
|
- `docs/specs/studio/4. Assets Workspace Specification.md`.
|
||||||
+98
@@ -0,0 +1,98 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0068
|
||||||
|
ticket: pbs-lsp-go-to-definition
|
||||||
|
title: PBS go-to-definition uses editorial lookup and physical files
|
||||||
|
created: 2026-09-21
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, definition]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS go-to-definition uses editorial lookup and physical files
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS editor assistance already had compiler-backed completion, hover, and signature help (`LSN-0051`). Users still could not jump from a use to a declaration. Wave 1 explicitly deferred `go to definition`.
|
||||||
|
|
||||||
|
The remaining LSP navigation family (references, rename, workspace symbols, document links, hierarchy) needed a destination policy before those features could be honest. The risk was shipping a text search, a new `SymbolId` index, or virtual documents for stdlib before a real physical target existed.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS Go to Definition is the LSP projection of **physical declaration locations** on top of the **same editorial lookup hover already uses**.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0052`:
|
||||||
|
|
||||||
|
1. Resolve the identifier under the cursor through the hover path (locals, parameters, members, imports/supplementals, current-module top-level). Do not use text search or a new usage index.
|
||||||
|
2. Keep the capability on the existing aggregated `FrontendLanguageService`. Add a default-empty `definition` method and a generic location DTO. Do not add a Definition SPI.
|
||||||
|
3. Map PBS editorial spans inside `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`.
|
||||||
|
4. Jump only when `Span.fileId` maps to a **regular filesystem file**. Otherwise return an empty list. Do not create virtual documents, `untitled:` buffers, or synthetic URIs.
|
||||||
|
5. The destination is the canonical declaration, not the import-alias line. Overloads return every matching location.
|
||||||
|
6. Advertise `definitionProvider`. Partial coverage is valid. Keywords, source-less builtins, unresolved names, and virtual stdlib paths stay empty; hover is unchanged.
|
||||||
|
7. Analysis stays request-local, like hover. This discussion does not build references, rename, or snapshot cache.
|
||||||
|
|
||||||
|
Spec 23 §8.3 already listed definition as an optional editor capability. It now also states: a definition location must identify a compiler-known physical source file, or the response must be empty.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS editorial | `PbsEditorialSupportService.definition` reuses hover dispatch and attaches declaration `Span`s (`PbsEditorialLocation`). |
|
||||||
|
| Generic contract | `FrontendDefinitionLocation` (absolute path + offsets) and `FrontendLanguageService.definition` defaulting to `List.of()`. |
|
||||||
|
| PBS mapping | `PBSFrontendLanguageService` maps `FileId` through `fileTable` and keeps the location only if `Files.isRegularFile(path)`. |
|
||||||
|
| LSP | `LanguageServiceBridge.definition`, `definitionProvider`, `textDocument/definition`. Compile-only frontends return empty. |
|
||||||
|
| VS Code | Unchanged thin client. |
|
||||||
|
|
||||||
|
Stdlib and SDK modules are still registered under virtual paths such as `/virtual/stdlib/...`. Those handles are not regular files, so F12 on `Gfx.clear` is empty even though hover works. That is the physical-file rule, not a missing lookup.
|
||||||
|
|
||||||
|
The location payload (path + span of an already resolved symbol) is reusable later by references (`AGD-0043`) and rename (`AGD-0046`). Those indexes were not built here. Snapshots (`AGD-0051`) remain a later performance discussion, not a prerequisite for this request-local feature.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Same-file jump:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
helper(); // definition -> helper's declaration in this file
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Aliased import jumps to the original declaration span, not the `import` line:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Log as Logger } from @sdk:log;
|
||||||
|
Logger.info("hello");
|
||||||
|
```
|
||||||
|
|
||||||
|
If `@sdk:log` is only a virtual stdlib handle, definition is empty. If a project file owns the declaration and that file exists on disk, definition uses that path.
|
||||||
|
|
||||||
|
Builtins stay hover-only:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
let n: int = 1; // hover describes the builtin; definition is empty
|
||||||
|
```
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not implement definition as a second name search in `lsp-v1` or in the VS Code extension. It will break on imports, overloads, and members, then be thrown away when references arrive.
|
||||||
|
|
||||||
|
Do not open `/virtual/stdlib/...` or invent an `untitled:` document so stdlib F12 “does something”. Empty is the honest result until those sources are real files.
|
||||||
|
|
||||||
|
Do not pick the first overload location in the server. Return the full `Location[]`.
|
||||||
|
|
||||||
|
Do not wait for snapshot cache before definition. Hover is already request-local; definition follows that shape.
|
||||||
|
|
||||||
|
Do not split a new top-level definition service “for future languages”. PBS is a real consumer of the existing language-service surface (`LSN-0067`).
|
||||||
|
|
||||||
|
Do not treat this lesson as closing references, rename, outline, workspace symbols, or document links. Those agendas stay open. This lesson only locks the destination policy they can reuse.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0042` (Q1–Q6 = A)
|
||||||
|
- Decision: `DEC-0052`
|
||||||
|
- Plan: `PLN-0131`
|
||||||
|
- Spec 23 §8.3 — optional definition capability; physical-file-or-empty
|
||||||
|
- `LSN-0051` — wave 1 deferred go-to-definition
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for LSP
|
||||||
|
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
|
||||||
|
- `LSN-0067` — no SPI or virtual-document host without a real consumer
|
||||||
|
- Still open: `AGD-0043` references, `AGD-0045` workspace symbols, `AGD-0046` rename, `AGD-0051` snapshots, `AGD-0055` document links, `AGD-0056` hierarchy
|
||||||
+111
@@ -0,0 +1,111 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0069
|
||||||
|
ticket: pbs-lsp-find-references
|
||||||
|
title: PBS find-references is the physical inverse of definition
|
||||||
|
created: 2026-09-21
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, references]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS find-references is the physical inverse of definition
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS already had compiler-backed completion, hover, signature help, and go-to-definition (`LSN-0051`, `LSN-0068`). Users still could not ask where a resolved symbol is used. Text search confuses overloads, shadowing, members, comments, and coincidental names. Rename (`AGD-0046`) and hierarchy (`AGD-0056`) need an honest usage list before they exist.
|
||||||
|
|
||||||
|
The risk was inventing a `SymbolId` / `RefIndex`, waiting for snapshot cache (`AGD-0051`), or listing uses of stdlib APIs whose declarations are still virtual paths.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS Find References is the LSP projection of **physical usage sites** of the **same identity definition already returns**.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0053` (AGD-0043 Q1–Q6 = A):
|
||||||
|
|
||||||
|
1. Resolve the cursor through the definition path (locals, parameters, members, imports/supplementals, current-module top-level). Identity is that physical declaration-location set. Do not text-search. Do not add `SymbolId` or a persistent `RefIndex`.
|
||||||
|
2. A site is a usage when its definition locations intersect the cursor identity. Overloads follow that intersection.
|
||||||
|
3. If definition at the same offset is empty, references is empty.
|
||||||
|
4. Walk regular `fileTable` files from the current `analyze()` surface. Do not scan `/virtual/stdlib` or other non-regular handles.
|
||||||
|
5. Keep the capability on the existing aggregated `FrontendLanguageService`. Reuse `FrontendDefinitionLocation`. Map PBS spans in `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`. No References SPI.
|
||||||
|
6. Honor LSP `includeDeclaration` in the server: union usage sites with definition locations when the host asks and the declaration is a regular file. No read/write classification.
|
||||||
|
7. Advertise `referencesProvider`. Partial coverage is valid. Analysis stays request-local. This discussion does not build rename, hierarchy, workspace symbols, virtual documents, or snapshot cache.
|
||||||
|
|
||||||
|
Spec 23 §8.3 now also states: a references location must identify a compiler-known physical source file; empty definition implies empty references; `includeDeclaration` must not invent a virtual location.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS editorial | `PbsEditorialSupportService.references` walks `IDENTIFIER` tokens and keeps sites whose `definition` locations intersect the cursor identity (`FileId` + start + end). |
|
||||||
|
| Generic contract | `FrontendLanguageService.references` defaults to `List.of()`. `FrontendEditorialContext.projectSurface` carries the PBS semantic read surface so the walk can see `astByFile`. |
|
||||||
|
| PBS mapping | `PBSFrontendLanguageService` requires a non-empty physical definition set, skips non-regular files, and maps surviving spans through the same `Files.isRegularFile` helper as definition. |
|
||||||
|
| LSP | `referencesProvider`, `textDocument/references`. The bridge applies `includeDeclaration` by unioning `references` with `definition`. Compile-only frontends stay empty. |
|
||||||
|
| VS Code | Unchanged thin client. |
|
||||||
|
|
||||||
|
Stdlib and SDK modules remain virtual (`/virtual/stdlib/...`). Shift+F12 on `Gfx.clear` is empty, matching F12. Hover is unchanged.
|
||||||
|
|
||||||
|
Local binding names are not usage sites: definition at `let total` is empty because the name is not yet in scope. The use `return total` matches. `includeDeclaration` adds the declaration span from definition, not a second name search.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Same-file function uses, including the declaring identifier (top-level names resolve to themselves):
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
helper();
|
||||||
|
helper();
|
||||||
|
// helper // not a reference
|
||||||
|
let text = "helper"; // not a reference
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Imported project (or otherwise physical) symbols collect uses in the importing file. Identity is the foreign declaration span.
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Log as Logger } from @sdk:log;
|
||||||
|
Logger.info("a");
|
||||||
|
Logger.info("b");
|
||||||
|
```
|
||||||
|
|
||||||
|
If `@sdk:log` is only a virtual handle, definition is empty, so references is empty.
|
||||||
|
|
||||||
|
Builtins stay hover-only:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
let n: int = 1; // hover works; references is empty
|
||||||
|
```
|
||||||
|
|
||||||
|
`includeDeclaration=true` adds the canonical declaration location on top of identifier usage sites. `false` returns usages only.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not implement find-references as workspace text search in `lsp-v1` or in the VS Code extension. It will lie about overloads, members, and imports, then poison rename.
|
||||||
|
|
||||||
|
Do not add a `SymbolId` index “for rename later”. Definition already gave the key: physical declaration locations. Rename can consume this list once it has its own decision.
|
||||||
|
|
||||||
|
Do not wait for snapshot cache. The LSP already reanalyzes on each editorial request. Snapshots (`AGD-0051`) can make the walk cheaper without changing the contract.
|
||||||
|
|
||||||
|
Do not treat empty stdlib references as a missing feature. Virtual paths are not regular files. Empty is the honest result until those sources live on disk.
|
||||||
|
|
||||||
|
Do not expect `let total` to appear as a usage of `total`. Inverse-of-definition only keeps identifier sites that themselves resolve. The declaration span arrives through `includeDeclaration`.
|
||||||
|
|
||||||
|
Do not put `includeDeclaration` into PBS types. It is a host flag applied in the LSP bridge.
|
||||||
|
|
||||||
|
Do not scan `/virtual/stdlib` to “find more uses”. That reopens virtual documents.
|
||||||
|
|
||||||
|
Do not split a References SPI “for future languages”. PBS is a real consumer of `FrontendLanguageService` (`LSN-0067`).
|
||||||
|
|
||||||
|
Do not treat this lesson as closing rename, snapshots, workspace symbols, document links, or hierarchy.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0043` (Q1–Q6 = A)
|
||||||
|
- Decision: `DEC-0053`
|
||||||
|
- Plan: `PLN-0132`
|
||||||
|
- Spec 23 §8.3 — optional navigation; physical-file-or-empty; empty definition implies empty references
|
||||||
|
- `LSN-0068` — definition identity this feature inverts
|
||||||
|
- `LSN-0051` — wave 1 deferred navigation
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for LSP
|
||||||
|
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
|
||||||
|
- `LSN-0067` — no SPI without a real in-repo consumer
|
||||||
|
- Still open: `AGD-0046` rename, `AGD-0045` workspace symbols, `AGD-0051` snapshots, `AGD-0055` document links, `AGD-0056` hierarchy
|
||||||
+141
@@ -0,0 +1,141 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0070
|
||||||
|
ticket: pbs-lsp-document-symbols-outline
|
||||||
|
title: PBS outline is an AST-backed document-symbol tree
|
||||||
|
created: 2026-09-21
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, outline, document-symbols]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS outline is an AST-backed document-symbol tree
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS already had compiler-backed completion, hover, signature help, go-to-definition (`LSN-0068`), and find-references (`LSN-0069`). VS Code Outline stayed empty. Long `.pbs` files had to be scanned by hand.
|
||||||
|
|
||||||
|
The risk was building outline from semantic success (so the tree vanishes while typing), flattening to `SymbolInformation`, inventing a Document Symbol SPI, or stuffing workspace search and folding into the same payload.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS Document Symbols is the LSP projection of the **named declaration tree of the open `.pbs` file**, with the **recovered AST as backbone**.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0054` (AGD-0044 Q1 A, Q2 AST tree, Q3 A, Q4 A, Q5 A, Q6 `.pbs`-only, Q7 existing kinds):
|
||||||
|
|
||||||
|
1. Presence, hierarchy, and ranges come from the document AST. Kind and `detail` may use cheap semantic enrichment. Semantics must not drop a named declaration still in the syntax tree, and must not require full analysis.
|
||||||
|
2. Named `TopDecl` plus syntactic members:
|
||||||
|
- `fn` → Function, no children;
|
||||||
|
- `declare struct` → Struct, children: fields, `ctor`s, methods;
|
||||||
|
- `declare service` → Service, children: methods;
|
||||||
|
- `declare contract` → Contract, children: signatures as methods;
|
||||||
|
- `declare host` → Host, children: signatures;
|
||||||
|
- `declare builtin type` → Builtin type, children: projection fields and signatures;
|
||||||
|
- `declare enum` → Enum, children: cases;
|
||||||
|
- `declare error` → Error, children: labels;
|
||||||
|
- `declare callback` → Callback, no children;
|
||||||
|
- `declare global` / `const` → Global / Const, no children;
|
||||||
|
- `implements Contract for Owner` → top-level Contract named `contractName`, `detail` = owner name, children: methods.
|
||||||
|
Locals, parameters, `this`, imports, and comments stay out. Private fields stay in. Overloads stay siblings. Host and builtin type appear only if the open file declares them.
|
||||||
|
3. Recovered AST is enough. Unnamed `InvalidDecl` is omitted. Named decls survive later semantic errors. No `PbsAst.File` → empty list. Do not invent nodes from text or token pairs.
|
||||||
|
4. Keep the capability on aggregated `FrontendLanguageService.documentSymbols` (default empty) plus a hierarchical DTO (`name`, `kind`, optional `detail`, range offsets, selection offsets, `children`). No file path on the DTO. PBS builds the tree in `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`. No Document Symbol SPI.
|
||||||
|
5. Advertise `documentSymbolProvider`. Payload is hierarchical `DocumentSymbol`, not flat `SymbolInformation`. `range` is the declaration span. `selectionRange` is the name span only if the AST already has one; this wave reuses the declaration span. Do not scan tokens for identifier spans. VS Code stays a thin client.
|
||||||
|
6. First wave is the current `.pbs` only. Out: imported supplementals, `mod.barrel`, locals, parameters, imports, comments, virtual documents, workspace symbols, folding, rename, snapshot cache. Server order is AST declaration order, not alphabetical.
|
||||||
|
7. Reuse `FrontendSymbolKind` / `PbsEditorialSymbolKind`. LSP projects to the closest host `SymbolKind`. Name is the identifier. `detail` may carry the AST signature (`(a: int) -> int`). Attributes such as `[Init]` do not enter the name.
|
||||||
|
|
||||||
|
Outline does not jump to another file. The physical-file destination policy of definition/references is not the outline policy.
|
||||||
|
|
||||||
|
Spec 23 §8.3 now also states: document symbols are the named declaration tree of the requested document; recovered syntax is enough; a missing syntax tree is empty; this is not a workspace index, folding ranges, or a foreign-file navigation list.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS editorial | `PbsAstDocumentSymbols` walks `PbsAst.File.topDecls` in source order. `PbsEditorialSupportService.documentSymbols` delegates to that walk. |
|
||||||
|
| Generic contract | `FrontendLanguageService.documentSymbols` defaults to `List.of()`. `FrontendDocumentSymbol` is hierarchical and pathless. |
|
||||||
|
| PBS mapping | `PBSFrontendLanguageService` requires `editorialContext.syntaxTree()` to be `PbsAst.File`. Barrels and unknown trees stay empty. Kinds map with `valueOf(kind.name())`. |
|
||||||
|
| LSP | `documentSymbolProvider`, `textDocument/documentSymbol`, hierarchical `DocumentSymbol`. Nested enum/error children project to `EnumMember`. Compile-only frontends stay empty. |
|
||||||
|
| VS Code | Unchanged thin client. |
|
||||||
|
|
||||||
|
`mod.barrel` is assembled as `BarrelFile`, not `PbsAst.File`, so `astByFile` has no barrel outline. Empty is the honest first-wave result.
|
||||||
|
|
||||||
|
Error case labels have no per-label span in the AST. Children reuse the parent `ErrorDecl` span rather than scanning tokens.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Outline of a file is the declarations in that file, not imports or locals:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Log } from @sdk:log;
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
let local = 1;
|
||||||
|
helper(local);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Outline: `helper`, `frame`. Not `Log`, not `local`.
|
||||||
|
|
||||||
|
Struct members and overloads as siblings:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
declare struct Vec(x: int) {
|
||||||
|
ctor make(x: int) { return; }
|
||||||
|
fn blend(dx: int, dy: int) -> int { return dx; }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
fn helper(value: int) -> int { return value; }
|
||||||
|
```
|
||||||
|
|
||||||
|
Outline: `Vec` (`x`, `make`, `blend`), then two `helper` siblings. Private field `x` is present. `detail` on `blend` is `(dx: int, dy: int) -> int`.
|
||||||
|
|
||||||
|
Recovered parse keeps the named decl:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
declare ;
|
||||||
|
fn ok() -> int { return 1; }
|
||||||
|
```
|
||||||
|
|
||||||
|
Outline: `ok`. The unnamed `InvalidDecl` is omitted.
|
||||||
|
|
||||||
|
`[Init] fn init()` still names the symbol `init`.
|
||||||
|
|
||||||
|
`implements TickLike for Point` is a top-level node named `TickLike` with detail `Point`.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not wait for semantic analysis to succeed before showing outline. The tree must survive broken intermediate edits.
|
||||||
|
|
||||||
|
Do not omit private fields because they are not in `mod.barrel`. Outline is for the author of this file.
|
||||||
|
|
||||||
|
Do not collapse overloads. AST identity forbids merging declaration sets.
|
||||||
|
|
||||||
|
Do not walk `File.imports` or supplemental imported `TopDecl`s. Those symbols are not declared in this document.
|
||||||
|
|
||||||
|
Do not implement outline for `mod.barrel` in this contract. Barrel AST is a different root. Empty is correct until a later decision.
|
||||||
|
|
||||||
|
Do not scan tokens to invent a tighter `selectionRange`. This wave uses the declaration span.
|
||||||
|
|
||||||
|
Do not put a file path on `FrontendDocumentSymbol`. The host already has the document URI. Outline is not go-to-definition.
|
||||||
|
|
||||||
|
Do not reuse the physical-file jump rule of `LSN-0068` as an outline destination policy. Clicking outline stays inside the buffer.
|
||||||
|
|
||||||
|
Do not overload document symbols with folding or scope guides (`LSN-0034`, `AGD-0053`).
|
||||||
|
|
||||||
|
Do not split a Document Symbol SPI “for future languages”. PBS is a real consumer of `FrontendLanguageService` (`LSN-0067`).
|
||||||
|
|
||||||
|
Do not treat this lesson as closing workspace symbols, folding, rename, document links, or hierarchy.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0044` (Q1 A, Q2 AST tree, Q3 A, Q4 A, Q5 A, Q6 `.pbs`-only, Q7 existing kinds)
|
||||||
|
- Decision: `DEC-0054`
|
||||||
|
- Plan: `PLN-0133`
|
||||||
|
- Spec 23 §8.3 — optional document symbols; recovered AST tree of the requested document
|
||||||
|
- `LSN-0068` — definition is a jump; outline is not
|
||||||
|
- `LSN-0069` — references invert definition identity
|
||||||
|
- `LSN-0034` — do not overload document symbols with structural anchors
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for LSP
|
||||||
|
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
|
||||||
|
- `LSN-0067` — no SPI without a real in-repo consumer
|
||||||
|
- Still open: `AGD-0045` workspace symbols, `AGD-0046` rename, `AGD-0051` snapshots, `AGD-0053` folding, `AGD-0055` document links, `AGD-0056` hierarchy
|
||||||
+149
@@ -0,0 +1,149 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0071
|
||||||
|
ticket: pbs-lsp-workspace-symbols
|
||||||
|
title: PBS workspace symbols are a physical named-declaration search
|
||||||
|
created: 2026-09-21
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, workspace-symbols]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS workspace symbols are a physical named-declaration search
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS already had compiler-backed completion, hover, signature help, go-to-definition (`LSN-0068`), find-references (`LSN-0069`), and an AST-backed outline of the open `.pbs` file (`LSN-0070`). VS Code workspace search (`Ctrl+T` / `workspace/symbol`) stayed empty.
|
||||||
|
|
||||||
|
The risk was treating workspace symbols as a second outline, inventing a `SymbolId` index, waiting for snapshot cache (`AGD-0051`), or returning stdlib/SDK hits whose declarations are still virtual paths (`/virtual/stdlib`). Workspace symbols is a jump. Outline is not.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS Workspace Symbols is the LSP projection of a **flat named-declaration search** over **regular filesystem files** of the current analysis, flattening the **same outline set** and using the **same physical-file destination policy** as definition.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0055` (AGD-0045 Q1 A, Q2 A, Q3 A, Q4 A, Q5 A, Q6 first-wave exclusions):
|
||||||
|
|
||||||
|
1. Emit only declarations whose `fileTable` handle is a regular filesystem file. Virtual stdlib/SDK, including `/virtual/stdlib`, is omitted. Do not invent virtual documents, `untitled:` buffers, or synthetic URIs.
|
||||||
|
2. `workspace/symbol` does not require an open text document. The server obtains the project analysis surface (`astByFile` / `projectSurface`) from `analyze()`. Missing surface → empty list.
|
||||||
|
3. The set is the flatten, file by file, of the named-declaration tree locked by outline (`LSN-0070`):
|
||||||
|
- `fn` → Function;
|
||||||
|
- `declare struct` → Struct plus fields, `ctor`s, methods;
|
||||||
|
- `declare service` → Service plus methods;
|
||||||
|
- `declare contract` → Contract plus signatures;
|
||||||
|
- `declare host` → Host plus signatures;
|
||||||
|
- `declare builtin type` → Builtin type plus projection fields and signatures;
|
||||||
|
- `declare enum` → Enum plus cases;
|
||||||
|
- `declare error` → Error plus labels;
|
||||||
|
- `declare callback` → Callback;
|
||||||
|
- `declare global` / `const` → Global / Const;
|
||||||
|
- `implements Contract for Owner` → `contractName`, kind CONTRACT, `detail` = owner, plus methods.
|
||||||
|
Locals, parameters, `this`, imports, and comments stay out. Private fields stay in. Overloads stay sibling hits. Unnamed `InvalidDecl` is omitted. Named decls survive later semantic errors.
|
||||||
|
4. First wave is `.pbs` whose recovered root is `PbsAst.File`. `mod.barrel` (`BarrelFile`) stays empty. Presence, name, kind, `detail`, and spans come from recovered AST. Do not invent nodes from text search.
|
||||||
|
5. Query is a case-insensitive substring of `name` only. Blank query returns the full first-wave corpus. Do not match `detail`, path, `containerName`, or qualified `Vec.blend`. No fuzzy ranking, no `top N`. After the filter, order is stable by name, then path, then start offset.
|
||||||
|
6. `containerName` is the parent name for members and empty for top-level declarations. `detail` may repeat the outline AST signature. Attributes such as `[Init]` do not enter the name.
|
||||||
|
7. Keep the capability on aggregated `FrontendLanguageService`. Add `workspaceSymbols` (default empty) plus a flat DTO with `name`, `kind`, optional `detail`, `containerName`, absolute path, and offsets. Do not reuse pathless `FrontendDocumentSymbol`. PBS flattens in `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`. No Workspace Symbol SPI, `SymbolId`, `RefIndex`, or snapshot cache.
|
||||||
|
8. Advertise `workspaceSymbolProvider` when the frontend exposes a language service. Payload is flat `SymbolInformation`. Do not emit hierarchical `DocumentSymbol` on this request. Compile-only frontends stay empty. VS Code stays a thin client.
|
||||||
|
|
||||||
|
Spec 23 §8.3 now also states: workspace symbols are a flat search of named declarations in compiler-known physical source files of the current analysis; recovered syntax is enough; a missing analysis surface is empty; the request must not require an open document; a declaration without a physical file is omitted; this is not outline, folding, a persistent index, or navigation to virtual locations.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS editorial | `PbsAstWorkspaceSymbols` flattens `PbsAstDocumentSymbols` and filters by name. `PbsEditorialSupportService.workspaceSymbols(ast, query)` delegates to that flatten. |
|
||||||
|
| Generic contract | `FrontendWorkspaceRequest` (`projectRoot`, `query`). `FrontendWorkspaceSymbol` carries path. `FrontendLanguageService.workspaceSymbols` defaults to `List.of()`. `prepareEditorialContext(FrontendPhaseContext)` defaults to empty so a workspace request can obtain project surface without a `FileId`. |
|
||||||
|
| PBS mapping | Project-level `prepareEditorialContext` attaches `fileTable` + `astByFile`. Regular `PbsAst.File` entries are flattened; non-regular handles are skipped. Results sort by name, path, offset. |
|
||||||
|
| LSP | `workspaceSymbolProvider`, `workspace/symbol` on `PrometeuWorkspaceService` (no document URI). `CompilerLanguageServiceBridge` analyzes the project with an empty overlay map. Mapper emits flat `SymbolInformation`. Nested enum/error hits with a container project to `EnumMember`. Compile-only frontends stay empty. |
|
||||||
|
| VS Code | Unchanged thin client. |
|
||||||
|
|
||||||
|
`workspace/symbol` in this wave reads the project on disk. Unsaved editor overlays are not shared into the search. Empty is honest until a later overlay/snapshot decision.
|
||||||
|
|
||||||
|
`mod.barrel` is still `BarrelFile`, not `PbsAst.File`. Empty barrel hits are the honest first-wave result.
|
||||||
|
|
||||||
|
Error case labels still have no per-label span. Flattened children reuse the parent `ErrorDecl` span, same as outline.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Workspace search of a project file is the flatten of that file's outline, not imports or locals:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Log } from @sdk:log;
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
let local = 1;
|
||||||
|
helper(local);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Query `frame` → `frame`. Query `helper` → `helper`. Query empty → `helper`, `frame` (plus other physical decls), sorted. Not `Log`, not `local`.
|
||||||
|
|
||||||
|
Members keep a container; overloads stay siblings:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
declare struct Vec(x: int) {
|
||||||
|
ctor make(x: int) { return; }
|
||||||
|
fn blend(dx: int, dy: int) -> int { return dx; }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn helper() -> int { return 42; }
|
||||||
|
fn helper(value: int) -> int { return value; }
|
||||||
|
```
|
||||||
|
|
||||||
|
Query `blend` → method `blend` with `containerName` `Vec`. Query `helper` → two hits. Query `Vec.blend` → empty (this wave matches `name` only).
|
||||||
|
|
||||||
|
Stdlib remains hover-only while the handle is virtual:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Gfx } from @sdk:gfx;
|
||||||
|
Gfx.clear(0);
|
||||||
|
```
|
||||||
|
|
||||||
|
Query `Gfx` is empty. F12 on `Gfx.clear` is already empty (`LSN-0068`). Workspace search does not reopen that jump.
|
||||||
|
|
||||||
|
Recovered parse keeps the named decl:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
declare ;
|
||||||
|
fn ok() -> int { return 1; }
|
||||||
|
```
|
||||||
|
|
||||||
|
Query empty → `ok`. The unnamed `InvalidDecl` is omitted.
|
||||||
|
|
||||||
|
`[Init] fn init()` still names the symbol `init`.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not implement workspace symbols as workspace text search in `lsp-v1` or in the VS Code extension. It will lie about overloads, members, and imports.
|
||||||
|
|
||||||
|
Do not reuse `FrontendDocumentSymbol`. Outline is pathless because the host already has the document URI. Workspace symbols is a jump and must carry a path.
|
||||||
|
|
||||||
|
Do not require an open editor buffer to answer `workspace/symbol`. Analyze the project and walk `astByFile`.
|
||||||
|
|
||||||
|
Do not include `/virtual/stdlib` so Ctrl+T on `Gfx` “does something”. Empty is the honest result until those sources are regular files.
|
||||||
|
|
||||||
|
Do not wait for snapshot cache. References already walks the current analysis request-locally. Snapshots (`AGD-0051`) can make the walk cheaper without changing this contract.
|
||||||
|
|
||||||
|
Do not add a `SymbolId` index “for rename later”. Outline already named the declarations; definition already named the destination.
|
||||||
|
|
||||||
|
Do not match `containerName`, path, or `Vec.blend` in this wave. The query is a substring of `name`.
|
||||||
|
|
||||||
|
Do not emit hierarchical `DocumentSymbol` on `workspace/symbol`. That payload is outline.
|
||||||
|
|
||||||
|
Do not treat unsaved overlay absence as a missing feature of this contract. First-wave analysis is the project on disk.
|
||||||
|
|
||||||
|
Do not split a Workspace Symbol SPI “for future languages”. PBS is a real consumer of `FrontendLanguageService` (`LSN-0067`).
|
||||||
|
|
||||||
|
Do not treat this lesson as closing rename, snapshots, folding, document links, or hierarchy.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0045` (Q1 A, Q2 A, Q3 A, Q4 A, Q5 A, Q6 first-wave exclusions)
|
||||||
|
- Decision: `DEC-0055`
|
||||||
|
- Plan: `PLN-0134`
|
||||||
|
- Spec 23 §8.3 — optional workspace symbols; physical-file-or-omit; no open document required
|
||||||
|
- `LSN-0070` — outline set this feature flattens
|
||||||
|
- `LSN-0068` — physical-file destination this feature reuses
|
||||||
|
- `LSN-0069` — project `astByFile` walk already exists for references
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for LSP
|
||||||
|
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
|
||||||
|
- `LSN-0067` — no SPI without a real in-repo consumer
|
||||||
|
- Still open: `AGD-0046` rename, `AGD-0051` snapshots, `AGD-0053` folding, `AGD-0055` document links, `AGD-0056` hierarchy
|
||||||
+128
@@ -0,0 +1,128 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0072
|
||||||
|
ticket: pbs-lsp-rename-symbol
|
||||||
|
title: PBS rename is a validated physical workspace edit
|
||||||
|
created: 2026-09-22
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, rename]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS rename is a validated physical workspace edit
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS already had compiler-backed completion, hover, signature help, go-to-definition (`LSN-0068`), find-references (`LSN-0069`), outline (`LSN-0070`), and workspace symbols (`LSN-0071`). Users still could not rename a symbol through the editor. Manual text edits miss uses or rewrite unrelated overloads, comments, strings, and same-name declarations.
|
||||||
|
|
||||||
|
The risk was a file-local rename, a lexeme replace, a new `SymbolId` / `RefIndex`, snapshot cache (`AGD-0051`) as a prerequisite, virtual stdlib documents, or a successful empty `WorkspaceEdit` that pretends the symbol changed.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS Rename Symbol is the LSP projection of a **validated `WorkspaceEdit`** over **physical identifier spans** of the **same identity definition already returns**.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0056` (AGD-0046 Q1–Q6 = A):
|
||||||
|
|
||||||
|
1. Identity is the physical declaration-location set from definition. Do not text-search. Do not add `SymbolId` or a persistent `RefIndex`.
|
||||||
|
2. Sites are identifier tokens whose definition intersects that identity, plus identifier-sized declaration name spans. Overloads of the same name in the same owner rewrite together. Members rewrite only that member. Comments, strings, and homonyms of another identity stay.
|
||||||
|
3. Walk regular `fileTable` files of the current `analyze()` surface. Omit `/virtual/stdlib` and other non-regular handles. Every edit location must be a compiler-known physical source file.
|
||||||
|
4. Refuse when physical identity is empty: builtins, virtual stdlib/SDK, unresolved names, keywords, comments, strings, `this`, `Self`. Refuse `mod.barrel`. Refuse `declare error` case labels that have no per-label span.
|
||||||
|
5. Exception: a local or parameter name span is renameable even when definition at that offset is empty. Identity becomes that name span; uses are identifiers whose definition intersects it.
|
||||||
|
6. Refuse when the cursor lexeme is an import alias (`item.alias()` distinct from `item.name()`), including uses of that alias. Do not follow alias definition and rewrite the export. Export rename happens only when the cursor writes the original name. Export rewrite must not change `as Alias` tokens or uses that spell a differing alias.
|
||||||
|
7. `prepareRename` validates the cursor and returns the identifier range, or null. `rename` also validates the new name: PBS identifier, not a keyword, no collision in the same binding space (top-level `fn`/`service`/`global`/`const`, local/param in the same scope, field in the same struct, method in the same owner, case in the same enum), ignoring rewritten sites and the overload set. Failure is an LSP error. Never return a successful empty `WorkspaceEdit`. The server does not write files and does not rename paths.
|
||||||
|
8. Keep the capability on aggregated `FrontendLanguageService`. `prepareRename` defaults empty; `rename` defaults unsupported. PBS maps in `prometeu-frontend-pbs`. Common LSP must not import `p.studio.compiler.pbs.*`. No Rename SPI. Advertise `renameProvider` with `prepareProvider`. Compile-only stays unsupported. VS Code stays a thin client.
|
||||||
|
|
||||||
|
Spec 23 §8.3 now also states: rename is a validated workspace edit of identifier spans in compiler-known physical source files; identity is definition; local/param name spans remain renameable; alias, virtual, and error-label cursors refuse; invalid names and collisions are protocol errors, not empty success; the server does not write files; `prepareProvider` is advertised when rename is exposed.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS editorial | `PbsEditorialSupportService.planRename` builds identity from definition or local/param name span, refuses aliases and error labels, walks `IDENTIFIER` tokens whose definition intersects identity and whose lexeme is the original name, then validates identifier/keyword/collision. |
|
||||||
|
| Generic contract | `FrontendLanguageService.prepareRename` defaults empty. `rename` defaults `FrontendRenameResult.unsupported()`. `FrontendRenameEdit` is path + offsets + `newText`. Applied results reject an empty edit list. |
|
||||||
|
| PBS mapping | `PBSFrontendLanguageService` reuses `projectDocuments` and `toFrontendLocation`. Empty physical identity is refuse, even if editorial sites exist on virtual handles. |
|
||||||
|
| LSP | `renameSupported`, `prepareRename`, `rename`. Mapper advertises `RenameOptions.prepareProvider`. Refused rename is `ResponseErrorException`, not an empty `WorkspaceEdit`. Compile-only does not advertise. |
|
||||||
|
| VS Code | Unchanged thin client. |
|
||||||
|
|
||||||
|
Stdlib and SDK modules remain virtual (`/virtual/stdlib/...`). F2 on `Gfx.clear` is refused, matching empty F12 / Shift+F12. Hover is unchanged.
|
||||||
|
|
||||||
|
`let total` at the binding itself still has empty definition. Rename uses the name span as identity so F2 on the binding works.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Same-file function, including overloads and the declaring identifier. Comment and string stay:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
fn helper() -> int { return 1; }
|
||||||
|
fn helper(value: int) -> int { return value; }
|
||||||
|
|
||||||
|
fn frame() -> void {
|
||||||
|
helper();
|
||||||
|
helper(2);
|
||||||
|
// helper
|
||||||
|
let text = "helper";
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
F2 on `helper` → `aid` rewrites both declarations and both calls.
|
||||||
|
|
||||||
|
Local name span:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
fn frame() -> void {
|
||||||
|
let total = 1;
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
F2 on `let total` or on the use rewrites both identifier sites.
|
||||||
|
|
||||||
|
Alias is refused. Export rename keeps the local alias:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
import { Log as Logger } from @sdk:log;
|
||||||
|
Logger.info("a");
|
||||||
|
```
|
||||||
|
|
||||||
|
F2 on `Logger` or `Logger.info` is refused. F2 on a physical `Log` declaration rewrites the original name and `import { Log as Logger }`, and leaves `Logger` / `Logger.info`.
|
||||||
|
|
||||||
|
Builtins and virtual stdlib stay hover-only:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
let n: int = 1;
|
||||||
|
Gfx.clear(5);
|
||||||
|
```
|
||||||
|
|
||||||
|
Invalid new names (`fn`, `1ab`) and collisions (`helper` → existing `frame`) fail with an LSP error.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not implement rename as workspace text search in `lsp-v1` or in the VS Code extension. It will rewrite comments, strings, overloads of another identity, and import aliases.
|
||||||
|
|
||||||
|
Do not follow definition through an import alias. `Logger` currently resolves to `Log`'s span; a blind inverse-of-definition rename would rewrite the export.
|
||||||
|
|
||||||
|
Do not return a successful empty `WorkspaceEdit` for a refused cursor. The editor will treat that as “renamed”.
|
||||||
|
|
||||||
|
Do not skip the local/param name-span exception. F2 on `let total` is the common case, and definition there is empty.
|
||||||
|
|
||||||
|
Do not rewrite `declare error` case labels by using the parent `ErrorDecl` span. Those labels have no per-label span.
|
||||||
|
|
||||||
|
Do not wait for snapshot cache. Rename reuses the request-local walk already used by references.
|
||||||
|
|
||||||
|
Do not treat empty/refused stdlib rename as a missing feature. Virtual paths are not regular files.
|
||||||
|
|
||||||
|
Do not split a Rename SPI “for future languages”. PBS is a real consumer of `FrontendLanguageService` (`LSN-0067`).
|
||||||
|
|
||||||
|
Do not treat this lesson as closing snapshots, folding, document links, hierarchy, code actions, formatting, file rename, or local-alias rename.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0046` (Q1–Q6 = A)
|
||||||
|
- Decision: `DEC-0056`
|
||||||
|
- Plan: `PLN-0135`
|
||||||
|
- Spec 23 §8.3 — optional rename; physical-file-or-empty; alias refuse; error instead of empty success; `prepareProvider`
|
||||||
|
- Spec: `docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md` §4.3–4.4
|
||||||
|
- `LSN-0068` — definition identity this feature writes
|
||||||
|
- `LSN-0069` — physical inverse that supplies usage sites
|
||||||
|
- `LSN-0051` — wave 1 deferred rename
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for LSP
|
||||||
|
- `LSN-0047` — protocol stays in `lsp-v1`; compiler owns semantics
|
||||||
|
- `LSN-0067` — no SPI without a real in-repo consumer
|
||||||
|
- Still open: `AGD-0051` snapshots, `AGD-0053` folding, `AGD-0055` document links, `AGD-0056` hierarchy
|
||||||
+130
@@ -0,0 +1,130 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0073
|
||||||
|
ticket: pbs-lsp-code-actions
|
||||||
|
title: PBS quick fixes are frontend repairs transported by the LSP
|
||||||
|
created: 2026-09-22
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor, code-actions, quick-fix]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS quick fixes are frontend repairs transported by the LSP
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS diagnostics already reach the editor, but the server did not advertise `codeActionProvider`. A user could see a duplicate attribute or a bad `InitAllowed` and still had to repair it by hand.
|
||||||
|
|
||||||
|
The tempting shortcut was a code-to-edit table in the LSP. That shortcut does not work. Compiler `Diagnostic` values carry a stable code, phase, template, placeholders, span, and related locations, but the reserved-attribute reports use the short constructor: empty placeholders, and the English sentence is the only fine discriminator. `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` covers Doc without `markdown`, a wrong payload, empty markdown, an unknown argument, `InitAllowed` with arguments, an out-of-range `AssetLowering`, and a bad `Host` shape. A switch on the code cannot pick a safe edit without reading the message. Diagnostic wording is rendering, not identity. Code actions are an optional editorial capability: the frontend owns the meaning, and the LSP transports it.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
PBS quick fix is one `WorkspaceEdit` tied to one diagnostic of the requested physical document. The frontend produces the repair from the syntax tree. The LSP does not invent it.
|
||||||
|
|
||||||
|
Durable locks from `DEC-0057` (AGD-0047: scope A, producer B, residence B, first wave C):
|
||||||
|
|
||||||
|
1. This wave is quick fix only. No organize-imports, source action, refactor, function or struct stub, code lens, or server command.
|
||||||
|
2. The server does not write files. The client applies the edit.
|
||||||
|
3. Each repair names the stable diagnostic code, the primary span of that diagnostic, and exactly one local text edit. The LSP must not keep a code-to-edit table and must not read the diagnostic message to build the edit.
|
||||||
|
4. The repair is computed on `textDocument/codeAction` from the current document analysis. It is not a required field of compiler `Diagnostic`, and it is not published inside `publishDiagnostics`, including `data`.
|
||||||
|
5. `publishDiagnostics` carries the stable compiler code on `Diagnostic.code` so the client can echo it. Source, severity, message, and related information stay as they were. Those presentation questions remain with `AGD-0054`.
|
||||||
|
6. A repair is returned only when the request context contains a diagnostic with the same code and the same primary range. An empty diagnostic list returns an empty action list. An `only` filter that does not include quick fix returns an empty action list.
|
||||||
|
7. Each item is a QuickFix `CodeAction`, not a `Command`. The edit touches one file, the requested physical document, and contains one `TextEdit`. There is no lazy resolve.
|
||||||
|
8. A path that is not a compiler-known regular file, including `/virtual/stdlib`, gets no edit.
|
||||||
|
9. If the frontend does not expose the capability, the server does not advertise `codeActionProvider`. A request that arrives anyway returns an empty list, not a protocol error. Absence of a fix is not a refused cursor.
|
||||||
|
10. PBS exposes the capability. Another frontend does not gain it merely by having a language service.
|
||||||
|
11. The first wave is two shapes, not three diagnostic codes.
|
||||||
|
- For every extra reserved attribute the declaration validator already reports as `E_SEM_DUPLICATE_RESERVED_ATTRIBUTE`, delete exactly that occurrence's span. Do not delete the first occurrence, the declaration, or neighboring whitespace.
|
||||||
|
- For an `InitAllowed` attribute with a non-empty argument list on a host signature, the shape the validator reports as `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` when the file is an interface module, replace that attribute span with `[InitAllowed]`. Do not emit that repair for any other attribute that shares the code. `[InitAllowed()]` is not diagnosed today and gets no repair.
|
||||||
|
12. Nothing else gets a quick fix in this wave. In particular: inserting `[Doc(markdown = """""")]` or any other Doc rewrite, inserting an empty or incomplete `[Host]` or `[BuiltinType]`, `W_SEM_IGNORED_VALUE`, unresolved imports, an invalid reserved-attribute target, parse errors, unresolved overloads, and method stubs.
|
||||||
|
|
||||||
|
`AGD-0048` still owns formatting. `AGD-0049` still owns import assistance and organize-imports. `AGD-0054` still owns range, related locations, and diagnostic presentation. The PBS diagnostics spec does not gain a mandatory remediation field.
|
||||||
|
|
||||||
|
Spec 23 §8.3 now states the shared contract: code actions are quick fixes only; the frontend produces each repair from the document syntax; tooling transports it and does not parse the message or switch on codes; the published diagnostic carries the stable code; a repair is returned only for a matching context diagnostic; the edit is one physical file; the server does not write files, return a command, or require resolve; a missing capability is an empty list, not an error; virtual documents get no edit.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
| Layer | What landed |
|
||||||
|
|---|---|
|
||||||
|
| PBS repairs | `PbsQuickFixCollector` walks the same attribute surfaces as `PbsDeclarationSemanticsValidator`, including the interface-module gate. Duplicate reserved attributes become an empty replacement of the extra span. The first `InitAllowed` with arguments on an interface host signature becomes `[InitAllowed]`. |
|
||||||
|
| Source kind | `PbsSemanticReadSurface.sourceKindByFile` records the kind used to parse each file. A missing kind means project rules, so a project `declare host` does not pretend the validator emitted the interface-only `InitAllowed` diagnostic. |
|
||||||
|
| Generic contract | `FrontendLanguageService.codeActionsSupported` defaults false. `codeActions` defaults empty. `FrontendCodeAction` is title, diagnostic code, path, offsets, and `newText`. Empty `newText` is a deletion and is allowed. |
|
||||||
|
| PBS mapping | `PBSFrontendLanguageService` exposes the capability and returns repairs only for the requested regular file. `/virtual/stdlib` fails `Files.isRegularFile` and produces nothing. |
|
||||||
|
| LSP | `BaselineDocumentIssue.code` is copied onto `Diagnostic.code`. `data` stays unset. The bridge drops repairs whose code and range do not match a context diagnostic. `PrometeuTextDocumentService.codeAction` honors the quick-fix `only` filter and never fails the request for “no fix”. |
|
||||||
|
| Protocol | `codeActionProvider` is `CodeActionOptions` with kind `quickfix` and `resolveProvider` false, and only when the frontend reports support. Mapped actions are `CodeAction` values with a `WorkspaceEdit`. They are not `Command`s. |
|
||||||
|
|
||||||
|
Titles are `Remove duplicate reserved attribute` and `Remove InitAllowed arguments`.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Duplicate `Doc` on a project file. The first copy stays. Each later copy is deleted at its own span:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
[Doc(markdown = """
|
||||||
|
First.
|
||||||
|
""")]
|
||||||
|
[Doc(markdown = """
|
||||||
|
Second.
|
||||||
|
""")]
|
||||||
|
fn duplicated() -> void { return; }
|
||||||
|
```
|
||||||
|
|
||||||
|
The quick fix removes the second attribute and leaves `First.`. A context diagnostic with the same range but code `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` produces no action. An empty diagnostic list produces no action.
|
||||||
|
|
||||||
|
Malformed or empty Doc is visible and not repairable here:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
[Doc(text = """
|
||||||
|
Wrong argument.
|
||||||
|
""")]
|
||||||
|
fn malformed() -> void { return; }
|
||||||
|
```
|
||||||
|
|
||||||
|
`InitAllowed` with arguments is repaired only on an interface-module host signature:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
declare host Gfx {
|
||||||
|
[Host(module = "gfx2d", name = "clear", version = 1)]
|
||||||
|
[InitAllowed(flag = 1)]
|
||||||
|
fn clear() -> void;
|
||||||
|
|
||||||
|
[Host(module = "gfx2d", name = "fill", version = 1)]
|
||||||
|
[InitAllowed()]
|
||||||
|
fn fill() -> void;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`clear` becomes `[InitAllowed]`. `fill` is already valid to the validator, so `[InitAllowed()]` is left alone. The same `InitAllowed(flag = 1)` inside a project file does not get that repair, because the validator does not emit the malformed-attribute diagnostic there.
|
||||||
|
|
||||||
|
The same collector deletes the extra copy of `BuiltinType`, `IntrinsicCall`, `BuiltinConst`, `Host`, and `AssetLowering` when the validator reports `E_SEM_DUPLICATE_RESERVED_ATTRIBUTE` for that surface. A malformed `Host` that merely shares the malformed-attribute code gets no edit.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not choose the edit in `prometeu-lsp` by switching on `E_SEM_MALFORMED_RESERVED_ATTRIBUTE` or by parsing the English message. The code is too coarse, and the message is not the identity.
|
||||||
|
|
||||||
|
Do not store the repair on compiler `Diagnostic` or in `Diagnostic.data`. Compilation and quick fix stay different surfaces. The published code exists so the client can echo it back.
|
||||||
|
|
||||||
|
Do not match on `Diagnostic.source` as if it were the long-term identity field. Today the bridge still copies the code into `source` for the existing presentation. The code-action match uses `Diagnostic.code`. `AGD-0054` may change `source` later.
|
||||||
|
|
||||||
|
Do not delete the first duplicate, and do not trim the whitespace around the deleted span. That cleanup is formatting and belongs to `AGD-0048`.
|
||||||
|
|
||||||
|
Do not insert `[Doc(markdown = """""")]`, an empty `[Host]`, or an empty `[BuiltinType]`. Those edits trade one diagnostic for another, or invent a declaration.
|
||||||
|
|
||||||
|
Do not treat `W_SEM_IGNORED_VALUE` as a source edit. Discard exists in lowering, not as PBS syntax.
|
||||||
|
|
||||||
|
Do not offer the `InitAllowed` rewrite for `[InitAllowed()]` or for a project file. The validator does not diagnose those shapes as “arguments not allowed”, so there is no diagnostic to attach.
|
||||||
|
|
||||||
|
Do not return a protocol error when there is no fix. Rename refuses a bad cursor with an error. Quick fix answers “nothing to do” with an empty list.
|
||||||
|
|
||||||
|
Do not advertise `codeActionProvider` for every frontend that has a language service. The default capability is unsupported.
|
||||||
|
|
||||||
|
Do not treat this lesson as closing formatting, import assistance, diagnostic presentation, snapshots, folding, document links, or hierarchy.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Agenda: `AGD-0047` (scope A, producer B, residence B, first wave C)
|
||||||
|
- Decision: `DEC-0057`
|
||||||
|
- Plan: `PLN-0136`
|
||||||
|
- Spec 23 §8.3 — optional code actions; frontend-owned repair; match by code and range; empty list when unsupported
|
||||||
|
- Spec: `docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md` — wording is not identity; remediation stays outside the v1 diagnostic minimum
|
||||||
|
- `LSN-0056` — code actions are an optional editorial capability
|
||||||
|
- `LSN-0058` — generic `FrontendLanguageService` for the LSP
|
||||||
|
- `LSN-0067` — no new editorial SPI without a real consumer; PBS implements the existing language service
|
||||||
|
- Still open: `AGD-0048` formatting, `AGD-0049` import assistance, `AGD-0054` diagnostics UX, `AGD-0051` snapshots, `AGD-0056` hierarchy
|
||||||
+74
@@ -0,0 +1,74 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0055
|
||||||
|
ticket: multi-frontend-provider-contract
|
||||||
|
title: Static frontend providers before plugin architecture
|
||||||
|
created: 2026-07-15
|
||||||
|
tags: [compiler, compiler-general, studio, frontend, registry, multi-frontend]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Prometeu needed a multi-frontend boundary without turning the compiler or Studio into a dynamic plugin platform. Before this work, shared code could ask the registry for frontend specs or phase services, and PBS was registered directly as the default language. That worked for a single frontend, but it made the next frontend harder because common code could still depend on PBS-specific construction details.
|
||||||
|
|
||||||
|
The durable ownership rule is now: common compiler and Studio code select a frontend by `languageId`, then consume a provider contract. PBS remains the first and only real provider, but it is no longer the shape of the shared abstraction.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### `FrontendProvider` is the common registration unit
|
||||||
|
|
||||||
|
**What:** Each registered frontend is represented by a `FrontendProvider` with:
|
||||||
|
|
||||||
|
- `specification()`, for the static frontend contract and `languageId`;
|
||||||
|
- `compiler()`, for compiler-facing frontend execution;
|
||||||
|
- `languageService()`, as an optional editor-facing capability.
|
||||||
|
|
||||||
|
**Why:** This groups the frontend identity, compiler entrypoint, and optional tooling capability without forcing every frontend to implement Studio/editor services.
|
||||||
|
|
||||||
|
**Trade-offs:** The provider is intentionally small. It does not solve dynamic discovery, plugin installation, external loading, or all future language-service APIs. Those are separate architectural decisions.
|
||||||
|
|
||||||
|
### Registration is explicit
|
||||||
|
|
||||||
|
**What:** Frontend registration is static and composition-root-owned. The application composition path bootstraps the default provider set, and the registry resolves providers by `languageId`.
|
||||||
|
|
||||||
|
**Why:** Explicit registration keeps dependencies visible and testable. It lets composition know about PBS while preventing common compiler and Studio consumers from directly constructing PBS services.
|
||||||
|
|
||||||
|
**Trade-offs:** Adding a new in-repository frontend still requires a code change in composition. That is acceptable because this decision optimizes for repository-internal multi-frontend readiness, not external plugin extensibility.
|
||||||
|
|
||||||
|
### PBS is a provider, not the shared model
|
||||||
|
|
||||||
|
**What:** PBS is wrapped by `PBSFrontendProvider`. Shared build and Studio consumers obtain frontend behavior through `FrontendRegistryService.require(languageId)` or provider-derived listings.
|
||||||
|
|
||||||
|
**Why:** PBS remains the correctness baseline, but it must not become the exclusive owner of compiler pipeline semantics.
|
||||||
|
|
||||||
|
**Trade-offs:** PBS-specific tests may still instantiate `PBSFrontendPhaseService` directly because they test PBS internals. Common modules should not.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
Use this path for common compiler execution:
|
||||||
|
|
||||||
|
1. Resolve the project language from the manifest or default provider.
|
||||||
|
2. Resolve `FrontendProvider` by `languageId`.
|
||||||
|
3. Use `provider.specification()` for static metadata.
|
||||||
|
4. Use `provider.compiler()` for frontend compilation.
|
||||||
|
5. Use `provider.languageService()` only when a tooling consumer needs optional editor services.
|
||||||
|
|
||||||
|
Use this path for Studio language catalogs:
|
||||||
|
|
||||||
|
1. List providers from the registry.
|
||||||
|
2. Derive templates from `provider.specification()`.
|
||||||
|
3. Do not hardcode PBS templates in Studio catalog code.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- Do not add reflection, classpath scanning, external JAR loading, or runtime plugin installation to solve repository-internal frontend registration.
|
||||||
|
- Do not make `languageService()` mandatory. Compilation and editor assistance are separate capabilities.
|
||||||
|
- Do not instantiate `PBSFrontendPhaseService` from common build, dependency, Studio, or app code.
|
||||||
|
- Do not use PBS as a fallback for unknown `languageId`. Unknown languages must fail explicitly.
|
||||||
|
- Do not move frontend semantic ownership into Studio just because Studio consumes provider metadata.
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- Static providers are enough to prepare for multiple in-repository frontends.
|
||||||
|
- The registry boundary is provider-based, not PBS-based.
|
||||||
|
- Composition may know which frontends exist; common consumers should only know `FrontendProvider`.
|
||||||
|
- Optional editor capabilities keep compiler readiness independent from Studio feature depth.
|
||||||
+88
@@ -0,0 +1,88 @@
|
|||||||
|
# Compile-first frontends with optional editorial capabilities
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
Prometeu is moving from a PBS-centered compiler/editor stack toward a multi-frontend compiler. PBS already provides compilation plus rich editor assistance, so it was easy for shared code, LSP, or Studio consumers to assume that every frontend can provide diagnostics, semantic tokens, completion, hover, and signature help as one package.
|
||||||
|
|
||||||
|
That assumption makes future frontend adoption too expensive. A new frontend must be able to compile before it has a complete IDE experience.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
The frontend contract is compile-first.
|
||||||
|
|
||||||
|
Every frontend must provide a compiler capability through `FrontendProvider.compiler()`. Editorial services are optional and live behind `FrontendProvider.languageService()`.
|
||||||
|
|
||||||
|
A frontend that can compile but has no language service is valid. Missing editor assistance must not block `analyze`, `compile`, `build`, backend lowering, bytecode emission, verification, or artifact writing.
|
||||||
|
|
||||||
|
LSP and Studio consumers must query editorial capability before invoking editor-specific behavior. Absence of a capability is a normal state, not a compiler failure.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
The compiler pipeline spec now defines the provider boundary explicitly:
|
||||||
|
|
||||||
|
- `compiler()` is the only required executable frontend capability.
|
||||||
|
- `languageService()` is optional.
|
||||||
|
- editor capabilities such as completion, hover, definition, signature help, semantic tokens, formatting, rename, and code actions are optional unless a future accepted decision narrows the requirement.
|
||||||
|
- absent editor capabilities have deterministic fallback behavior.
|
||||||
|
- compiler diagnostics and editor diagnostics are separate ownership surfaces.
|
||||||
|
|
||||||
|
PBS keeps its rich editor assistance, but now exposes it through `PBSFrontendLanguageService`, returned by `PBSFrontendProvider.languageService()`.
|
||||||
|
|
||||||
|
The LSP bridge resolves the active `FrontendProvider` and checks for `languageService()` before using editor behavior. For now, PBS remains an adapter-specific implementation because the common language-service DTOs are not yet generalized. That is acceptable because the important boundary is already enforced: the LSP no longer assumes that compiler support implies editor support.
|
||||||
|
|
||||||
|
Conformance coverage now includes:
|
||||||
|
|
||||||
|
- a compile-only provider fixture with no language service;
|
||||||
|
- LSP neutral responses when editor capability is absent;
|
||||||
|
- PBS regression coverage for existing completion, hover, signature help, semantic tokens, and documentation behavior;
|
||||||
|
- architecture tests preventing common modules from directly instantiating PBS editor support.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
A compile-only frontend should look like this at the provider boundary:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public final class ExampleFrontendProvider implements FrontendProvider {
|
||||||
|
@Override
|
||||||
|
public FrontendSpec specification() {
|
||||||
|
return EXAMPLE_SPEC;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FrontendPhaseService compiler() {
|
||||||
|
return exampleCompiler;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
It does not need to override `languageService()`. The default empty optional is a valid frontend state.
|
||||||
|
|
||||||
|
An editor consumer should treat missing services as a normal fallback:
|
||||||
|
|
||||||
|
```java
|
||||||
|
return provider.languageService()
|
||||||
|
.filter(ExpectedLanguageService.class::isInstance)
|
||||||
|
.map(ExpectedLanguageService.class::cast)
|
||||||
|
.map(service -> service.completion(...))
|
||||||
|
.orElseGet(List::of);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not use PBS as the minimum frontend contract. PBS is the first rich frontend, not the definition of frontend validity.
|
||||||
|
|
||||||
|
Do not make editor diagnostics a prerequisite for compilation. Build/analyze diagnostics are compiler output; live editor diagnostics may reuse compiler results but have different latency, cancellation, overlay, and UX concerns.
|
||||||
|
|
||||||
|
Do not split the language service into many top-level interfaces before implementation pressure proves a real lifecycle or ownership boundary. The current contract intentionally keeps an aggregated optional language-service surface.
|
||||||
|
|
||||||
|
Do not call PBS editorial classes directly from common compiler, LSP, Studio, or app code. Go through `FrontendProvider.languageService()` and adapter-local capability checks.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Spec: `docs/specs/compiler/23. Compiler Pipeline Entry Points Specification.md`
|
||||||
|
- Provider API: `prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendProvider.java`
|
||||||
|
- PBS language service: `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendLanguageService.java`
|
||||||
|
- LSP bridge: `prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java`
|
||||||
|
- Conformance tests:
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/specs/FrontendProviderBoundaryTest.java`
|
||||||
|
- `prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridgeTest.java`
|
||||||
+92
@@ -0,0 +1,92 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0058
|
||||||
|
ticket: multi-frontend-remove-pbs-branches
|
||||||
|
title: Generic Frontend Editorial Contract for LSP
|
||||||
|
created: 2026-07-15
|
||||||
|
tags: [compiler, compiler-general, compiler-pbs, studio, frontend, lsp, coupling, multi-frontend]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
Prometeu was preparing for multiple compiler frontends while the LSP bridge still knew too much about PBS internals. The first framing was broad: remove explicit PBS checks from common code. After inspection, that was too blunt.
|
||||||
|
|
||||||
|
PBS was already mostly centered in `prometeu-frontend-pbs`. Defaults, templates, `.pbs` fixtures, VS Code language registration, semantic keys, and composition-root bootstrap were legitimate PBS references. The real architectural problem was narrower: common LSP code imported and called PBS-specific editorial types and services for semantic tokens, completion, hover, signature help, and semantic read preparation.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
The common LSP/editorial path must consume frontend-provided editorial capabilities through generic contracts exposed by `prometeu-frontend-api`.
|
||||||
|
|
||||||
|
The provider contract remains stable:
|
||||||
|
|
||||||
|
1. `FrontendProvider.compiler()` is mandatory.
|
||||||
|
2. `FrontendProvider.languageService()` is optional.
|
||||||
|
3. Compile-only frontends are valid.
|
||||||
|
4. Unknown `languageId` values fail explicitly.
|
||||||
|
5. PBS may be the product default only when the user has not chosen a language.
|
||||||
|
|
||||||
|
PBS is not the shared editor model. PBS implements the generic contract from inside its frontend boundary.
|
||||||
|
|
||||||
|
## Final Implementation Shape
|
||||||
|
|
||||||
|
The implementation introduced generic frontend editorial DTOs and default methods in `FrontendLanguageService`:
|
||||||
|
|
||||||
|
1. `FrontendDocumentRequest`
|
||||||
|
2. `FrontendEditorialContext`
|
||||||
|
3. `FrontendCompletionCandidate`
|
||||||
|
4. `FrontendHover`
|
||||||
|
5. `FrontendSignatureHelp`
|
||||||
|
6. `FrontendSignature`
|
||||||
|
7. `FrontendSymbolKind`
|
||||||
|
8. `FrontendDocumentation`
|
||||||
|
|
||||||
|
`CompilerLanguageServiceBridge` now resolves the selected provider and calls generic `FrontendLanguageService` methods for semantic tokens, completion, hover, and signature help.
|
||||||
|
|
||||||
|
PBS-specific analysis setup moved behind `PBSFrontendLanguageService.prepareEditorialContext(...)`. The bridge no longer imports `p.studio.compiler.pbs.*`, no longer knows `PbsAst.File`, and no longer calls `PBSFrontendPhaseService.semanticReadSurface(...)` directly.
|
||||||
|
|
||||||
|
An architectural test now protects the common LSP code from reintroducing PBS implementation imports.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
A frontend with no language service remains valid:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public final class CompileOnlyFrontendProvider implements FrontendProvider {
|
||||||
|
@Override
|
||||||
|
public FrontendSpec specification() {
|
||||||
|
return SPEC;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FrontendPhaseService compiler() {
|
||||||
|
return compiler;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
An LSP consumer should resolve the selected provider, ask for `languageService()`, and fall back deterministically when editorial capability is absent.
|
||||||
|
|
||||||
|
PBS can still keep rich internal models such as `PbsEditorialResolvedSymbol`, but those models must be mapped to generic `FrontendHover`, `FrontendCompletionCandidate`, or `FrontendSignatureHelp` before common LSP consumes them.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not remove legitimate PBS defaults just because they mention PBS. PBS remains the product default when the user has not chosen another language.
|
||||||
|
|
||||||
|
Do not use PBS as a fallback for unknown `languageId`. Unknown language identity is a configuration error and must fail explicitly.
|
||||||
|
|
||||||
|
Do not make editor assistance mandatory. Compilation and editor support are separate frontend capabilities.
|
||||||
|
|
||||||
|
Do not move frontend semantic ownership into LSP or Studio. The LSP bridge transports frontend-owned editorial results; it does not author language semantics.
|
||||||
|
|
||||||
|
Do not reintroduce PBS imports in common LSP code for convenience. If a capability needs PBS-specific state, create or extend a frontend-owned generic boundary and keep the PBS mapping inside `prometeu-frontend-pbs`.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- `DEC-0042` locked the generic frontend editorial language-service contract.
|
||||||
|
- `PLN-0111` introduced generic frontend editorial DTOs and defaults.
|
||||||
|
- `PLN-0112` migrated semantic tokens.
|
||||||
|
- `PLN-0113` migrated completion.
|
||||||
|
- `PLN-0114` migrated hover and documentation.
|
||||||
|
- `PLN-0115` migrated signature help.
|
||||||
|
- `PLN-0116` removed PBS imports from common LSP and added boundary coverage.
|
||||||
|
- Related lesson: `LSN-0055` Static frontend providers before plugin architecture.
|
||||||
|
- Related lesson: `LSN-0056` Compile-first frontends with optional editorial capabilities.
|
||||||
+98
@@ -0,0 +1,98 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0059
|
||||||
|
ticket: multi-frontend-frontend-backend-contract
|
||||||
|
title: Common IRBackend handoff and backend guardrails
|
||||||
|
created: 2026-07-15
|
||||||
|
tags: [compiler, compiler-general, compiler-pbs, ir, backend, multi-frontend]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Common IRBackend handoff and backend guardrails
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The multi-frontend work needed a clear boundary between language-specific frontends and common backend stages.
|
||||||
|
|
||||||
|
The existing code was already close to the desired architecture: PBS parsing, AST construction, and semantic analysis lowered into `IRBackend`, while the backend consumed `IRBackend` and lowered it into `IRVM`. The risk was not a known broken dependency. The risk was that common backend behavior still looked PBS-owned in specs, names, and missing guardrails, which could invite future coupling when another frontend is introduced.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### `IRBackend` is the common executable handoff
|
||||||
|
|
||||||
|
**What:** `IRBackend` remains the normative frontend-to-backend executable handoff. Frontends emit it; common backend stages consume it.
|
||||||
|
|
||||||
|
**Why:** The existing model already provides a language-neutral executable contract with modules, callable identities, executable functions, instruction metadata, globals, synthetic functions, host calls, intrinsics, spans, and capabilities. Renaming or redesigning it without a concrete leak would add churn without improving the boundary.
|
||||||
|
|
||||||
|
**Trade-offs:** Keeping the name `IRBackend` means the architecture relies on documentation and tests to communicate its common role. That is acceptable because the name is already established and the guardrails now enforce the boundary.
|
||||||
|
|
||||||
|
### PBS owns lowering into `IRBackend`, not backend consumption of it
|
||||||
|
|
||||||
|
**What:** PBS specs describe PBS admission and translation into `IRBackend`. Compiler-general specs describe the common `IRBackend -> IRVM` contract and backend obligations.
|
||||||
|
|
||||||
|
**Why:** PBS is currently the only rich frontend producing executable `IRBackend`, so many examples naturally come from PBS. Specs must still separate source-language obligations from backend obligations so future frontends do not inherit PBS-specific rules by accident.
|
||||||
|
|
||||||
|
**Trade-offs:** Some PBS-facing examples remain useful, especially around lifecycle wrappers and asset metadata. They must be phrased as current frontend sources of a common backend obligation, not as backend ownership by PBS.
|
||||||
|
|
||||||
|
## Implementation Result
|
||||||
|
|
||||||
|
The completed work:
|
||||||
|
|
||||||
|
1. rewrote the general backend spec so `IRBackend -> IRVM` is explicitly compiler-general;
|
||||||
|
2. rewrote the PBS lowering spec so PBS emits the common handoff instead of owning backend behavior;
|
||||||
|
3. updated the conformance matrix with DEC-0043 guardrail rows;
|
||||||
|
4. added a direct backend test that manually constructs common `IRBackend` and lowers it without PBS parser or frontend services;
|
||||||
|
5. added an architectural test preventing common backend imports from `p.studio.compiler.pbs`;
|
||||||
|
6. added a reflection-based contract test preventing public `IRBackend` model types from exposing PBS packages;
|
||||||
|
7. renamed the common lifecycle helper from `validatePbsLifecycleStructure` to `validateCommonLifecycleStructure`.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
### Boundary consolidation before abstraction
|
||||||
|
|
||||||
|
When an existing boundary is already technically sound, prefer consolidation over redesign:
|
||||||
|
|
||||||
|
1. document the current contract as normative;
|
||||||
|
2. identify only concrete leaks;
|
||||||
|
3. add tests that would fail if the boundary regresses;
|
||||||
|
4. avoid renames or model extraction until there is evidence of real coupling.
|
||||||
|
|
||||||
|
This keeps multi-frontend preparation focused on preventing regressions rather than inventing abstractions prematurely.
|
||||||
|
|
||||||
|
### Guardrails for common backend neutrality
|
||||||
|
|
||||||
|
A useful backend neutrality guardrail has two layers:
|
||||||
|
|
||||||
|
1. source/package guard: common backend source must not import language frontend packages;
|
||||||
|
2. public-contract guard: common handoff types must not expose language-owned types through fields, constructors, methods, or record components.
|
||||||
|
|
||||||
|
The package guard catches implementation coupling. The reflection guard catches API coupling.
|
||||||
|
|
||||||
|
### Direct handoff construction test
|
||||||
|
|
||||||
|
A backend test should be able to construct executable `IRBackend` manually using only common model types and lower it through `LowerToIRVMService`.
|
||||||
|
|
||||||
|
That test proves the backend consumes the contract, not a specific frontend pipeline.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- Do not treat the presence of PBS examples as proof that the backend is PBS-owned.
|
||||||
|
- Do not move PBS source rules into compiler-general specs.
|
||||||
|
- Do not let lifecycle terms such as published wrapper, boot guard, or frame root hide whether the obligation is common or PBS-specific.
|
||||||
|
- Do not rename `IRBackend` for aesthetics when the real problem is missing ownership language and missing guardrails.
|
||||||
|
- Do not use a future synthetic test frontend as a substitute for simple direct `IRBackend` construction tests.
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- `IRBackend` is the common executable handoff.
|
||||||
|
- PBS owns PBS-to-`IRBackend` lowering; compiler-general owns `IRBackend -> IRVM`.
|
||||||
|
- Common backend code must not depend on `p.studio.compiler.pbs`.
|
||||||
|
- Public `IRBackend` contract types must not expose PBS AST, token, parser, semantic, or editorial types.
|
||||||
|
- Multi-frontend preparation should first lock existing good boundaries before introducing new abstractions.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
|
||||||
|
- `docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md`
|
||||||
|
- `docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/irvm/LowerToIRVMServiceTest.java`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/specs/CommonBackendArchitectureTest.java`
|
||||||
|
- `prometeu-compiler/prometeu-frontend-api/src/test/java/p/studio/compiler/models/IRBackendExecutableContractTest.java`
|
||||||
+82
@@ -0,0 +1,82 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0060
|
||||||
|
ticket: multi-frontend-serializable-ir
|
||||||
|
title: Data contract first for serializable IRBackend
|
||||||
|
created: 2026-07-15
|
||||||
|
tags: [compiler, compiler-general, ir, backend, serialization, multi-frontend]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Data contract first for serializable IRBackend
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
The compiler already had a common executable handoff: `IRBackend`. PBS emits it, and common backend stages consume it before lowering to `IRVM`.
|
||||||
|
|
||||||
|
The remaining risk was subtler than direct PBS coupling. A Java-only handoff can accidentally grow around process-local assumptions: callbacks, services, object identity, mutable global state, unordered collections, lazy values, or direct references between live objects. Those shapes can work inside one JVM and still make a future external frontend or out-of-process boundary expensive to add.
|
||||||
|
|
||||||
|
The work needed to keep the handoff serializable by design without choosing JSON, Protobuf, RPC, plugin loading, or a separate process too early.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
`IRBackend` is a data contract first.
|
||||||
|
|
||||||
|
Public `IRBackend` contract types must remain modelable as an acyclic, deterministic data graph made from primitives, strings, enums, immutable values, ordered lists, explicit ids, stable symbolic keys, and source attribution values such as file ids and spans.
|
||||||
|
|
||||||
|
The public handoff must not expose callbacks, lambdas, service objects, registries, visitors, live compiler services, frontend AST/parser/token/semantic/editorial objects, mutable global state, object identity semantics, unordered output-affecting collections, cyclic public references, process-dependent lazy values, or a selected wire format.
|
||||||
|
|
||||||
|
The important boundary is the data shape, not a codec. A future serializer should be able to consume the handoff because the public model is already disciplined, but this decision does not require a serializer to exist now.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
The implementation updated the compiler-general backend spec with a new `IRBackend` serializability-by-design subsection. The spec now states the allowed and forbidden public shapes and keeps wire format selection explicitly deferred.
|
||||||
|
|
||||||
|
The conformance matrix added `G20-4.2.x` rows for the new requirements:
|
||||||
|
|
||||||
|
- public `IRBackend` modelability as an acyclic deterministic data graph;
|
||||||
|
- rejection of callbacks, services, mutable or unordered collections, frontend-owned objects, process-dependent lazy values, cyclic public references, and wire-format commitments;
|
||||||
|
- use of explicit ids or stable symbolic keys for cross-object references.
|
||||||
|
|
||||||
|
The executable guardrails live in `IRBackendExecutableContractTest`:
|
||||||
|
|
||||||
|
- the public contract audit covers all current `p.studio.compiler.models` handoff types and nested value types;
|
||||||
|
- support types such as `FileId`, `ModuleId`, `CallableId`, `IntrinsicId`, `Span`, table reference records, and `ReadOnlyList` are explicitly classified;
|
||||||
|
- reflection checks inspect public fields, record components, public constructors, public methods, and generic type arguments;
|
||||||
|
- guardrails reject PBS/frontend exposure, callback shapes, service-like public shapes, mutable/unordered collection contracts, and other non-serializable public exposures;
|
||||||
|
- deterministic aggregation tests prove stable ordering for functions, synthetic functions, globals, executable functions, module pools, callable signatures, intrinsic pools, reserved metadata, and required capabilities;
|
||||||
|
- known references are locked to explicit ids or stable keys rather than direct object references.
|
||||||
|
|
||||||
|
The audit found no concrete public serialization leak that required changing the production model. That result is meaningful: the current `IRBackend` shape was already close to the target, so the correct implementation was spec clarification plus tests, not a redesign.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Good public handoff shapes:
|
||||||
|
|
||||||
|
- `ModuleId`, `CallableId`, `IntrinsicId`, and `FileId` for table-scoped references;
|
||||||
|
- `ReadOnlyList<T>` for ordered collections;
|
||||||
|
- `ModuleReference`, `CallableSignatureRef`, and `IntrinsicReference` as stable table values;
|
||||||
|
- `Span` for source attribution;
|
||||||
|
- enums and records for fixed value surfaces.
|
||||||
|
|
||||||
|
Bad public handoff shapes:
|
||||||
|
|
||||||
|
- `Map`, `Set`, or mutable collection interfaces where output order matters;
|
||||||
|
- `Runnable`, `Callable`, `Function`, visitors, or callbacks;
|
||||||
|
- compiler services or registries exposed as public fields or constructor parameters;
|
||||||
|
- frontend AST, parser, token, semantic, or editor types;
|
||||||
|
- direct references to another handoff object where an id or ordered table entry is the stable contract.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- Do not confuse "serializable by design" with "serialize it now." A codec is a future implementation detail.
|
||||||
|
- Do not add typed ids everywhere by taste. Add them when a real public field would otherwise depend on textual identity, object identity, or direct object references.
|
||||||
|
- Do not treat `ReadOnlyList` as cosmetic. Ordered collections are part of the deterministic contract.
|
||||||
|
- Do not let a private assembler or aggregator implementation shape leak into public handoff semantics.
|
||||||
|
- Do not move the rule into PBS specs. PBS owns how it populates the handoff; compiler-general owns the common handoff contract.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
|
||||||
|
- `docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md`
|
||||||
|
- `prometeu-compiler/prometeu-frontend-api/src/test/java/p/studio/compiler/models/IRBackendExecutableContractTest.java`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/specs/BackendConformanceMatrixSpecTest.java`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/irvm/LowerToIRVMServiceTest.java`
|
||||||
+143
@@ -0,0 +1,143 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0062
|
||||||
|
ticket: multi-frontend-common-lifecycle
|
||||||
|
title: Common lifecycle assembly after frontend declaration
|
||||||
|
created: 2026-09-19
|
||||||
|
tags: [compiler, compiler-general, compiler-pbs, lifecycle, backend, multi-frontend]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Common lifecycle assembly after frontend declaration
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
`IRBackend` was already the common executable handoff, but the PBS frontend still
|
||||||
|
owned two different jobs. It admitted language markers `[Init]`, `[Frame]`, and
|
||||||
|
`InitAllowed`, and it also assembled the platform lifecycle: module init,
|
||||||
|
project-init wrapper, published frame wrapper, physical entrypoint, and boot
|
||||||
|
guard.
|
||||||
|
|
||||||
|
That second job discovered roles through `__pbs.*` names and lived inside
|
||||||
|
`PBSFrontendPhaseService`. Another frontend could not reuse the boot sequence
|
||||||
|
without copying PBS. Common backend code also risked treating PBS naming as the
|
||||||
|
integration contract.
|
||||||
|
|
||||||
|
The old path had a concrete defect. The `[Init]` colocated with `[Frame]` is
|
||||||
|
project init, but it was also included in the file-init fragment. The published
|
||||||
|
wrapper then called module init and project init separately, so the same
|
||||||
|
callable could run twice. Specs required project init exactly once, after all
|
||||||
|
module initializers and before the frame root.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
Declaration and assembly are separate.
|
||||||
|
|
||||||
|
An executable frontend emits an immutable, ordered, typed
|
||||||
|
`IRLifecycleDeclaration` on `IRBackend`. The declaration carries:
|
||||||
|
|
||||||
|
- modules in explicit dependency order;
|
||||||
|
- each module's ordered file-init fragment references;
|
||||||
|
- an optional project-init callable;
|
||||||
|
- exactly one frame-root callable.
|
||||||
|
|
||||||
|
References use `ModuleId`, `FileId`, `CallableId`, a typed role, and source
|
||||||
|
attribution. Absence of a declaration means a deliberately non-executable
|
||||||
|
handoff. It must not synthesize a default `main`.
|
||||||
|
|
||||||
|
`FrontendPhasePipelineStage` stops at that declarative backend.
|
||||||
|
`AssembleLifecyclePipelineStage` runs immediately after it and is the terminal
|
||||||
|
stage of `analyze()`. `LifecycleAssemblerService` is the only owner of derived
|
||||||
|
lifecycle artifacts. `compile()` and `build()` reuse that single assembly pass.
|
||||||
|
|
||||||
|
`ResolveDepsPipelineStage` remains the ordering authority. Frontends propagate
|
||||||
|
that order; the assembler validates and applies it. Neither side may rebuild
|
||||||
|
order from synthetic names, `FileId`, textual module names, or incidental map
|
||||||
|
order.
|
||||||
|
|
||||||
|
Project init is excluded from file-init fragments and runs exactly once. Common
|
||||||
|
derived identities are neutral and deterministic. Common code must not import
|
||||||
|
PBS packages or inspect `__pbs.*` prefixes. Typed roles, ids, and origins are
|
||||||
|
the stable inspection surface; synthetic names are internal.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
PBS now emits per-file lifecycle contributions and a project-level declaration.
|
||||||
|
A colocated `[Init]` is the project-init reference only. File-init fragments
|
||||||
|
remain frontend-lowered executables, consumed by id and role rather than by
|
||||||
|
name prefix. `synthesizePublishedLifecycle` was removed.
|
||||||
|
|
||||||
|
The common assembler validates the declaration and materializes:
|
||||||
|
|
||||||
|
1. module init callables in declared module/file order;
|
||||||
|
2. an optional project-init wrapper, invoked once;
|
||||||
|
3. the published frame wrapper, which is the physical entrypoint;
|
||||||
|
4. a hidden boot guard that prevents a second bootstrap after success.
|
||||||
|
|
||||||
|
The declaration remains on the assembled `IRBackend` as provenance. IRVM
|
||||||
|
lowering keeps only assembled-graph preconditions such as wrapper identity,
|
||||||
|
synthetic origin, and boot-guard presence. It does not reconstruct lifecycle
|
||||||
|
from names.
|
||||||
|
|
||||||
|
`analyze()` still returns a fully assembled executable backend, without IRVM,
|
||||||
|
bytecode, or file output. Neutral names use the `__prometeu.lifecycle.*` prefix.
|
||||||
|
|
||||||
|
Diagnostics stay split: PBS reports marker, signature, placement, cardinality,
|
||||||
|
and colocation errors; the common layer reports unresolved ids, incompatible
|
||||||
|
roles, missing frame root, invalid origins, and frontend-preassembled derived
|
||||||
|
artifacts.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Good frontend output:
|
||||||
|
|
||||||
|
- a file with globals or a non-project `[Init]` contributes a
|
||||||
|
`FILE_INIT_FRAGMENT`;
|
||||||
|
- the `[Init]` next to `[Frame]` is `PROJECT_INIT` only;
|
||||||
|
- `[Frame]` is `FRAME_ROOT`;
|
||||||
|
- module order follows the resolved dependency graph even when names or file
|
||||||
|
ids would sort the other way.
|
||||||
|
|
||||||
|
Good assembled output:
|
||||||
|
|
||||||
|
- wrapper call order is module inits, then project init once, then frame root;
|
||||||
|
- boot guard is a hidden global, not a user global;
|
||||||
|
- `getLifecycleDeclaration()` still exposes the original typed references.
|
||||||
|
|
||||||
|
Bad output:
|
||||||
|
|
||||||
|
- PBS emitting `MODULE_INIT`, `PROJECT_INIT` wrappers, published wrappers, or
|
||||||
|
boot guards;
|
||||||
|
- common code matching `__pbs.frame_wrapper$m0` to discover the entrypoint;
|
||||||
|
- sorting modules by `FileId` or textual path because the declaration order was
|
||||||
|
inconvenient;
|
||||||
|
- leaving both the PBS assembler and the common stage active.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- Do not treat `analyze()` as "frontend only." It now includes common lifecycle
|
||||||
|
assembly so callers still receive an executable `IRBackend`.
|
||||||
|
- Do not keep a temporary dual path. Two assemblers duplicate wrappers or init.
|
||||||
|
- Do not infer missing frame roots or repair invalid declarations in the common
|
||||||
|
layer. Fail deterministically.
|
||||||
|
- Do not move PBS marker rules into the assembler. Language admission stays in
|
||||||
|
PBS; structural handoff checks stay common.
|
||||||
|
- Do not preserve `__pbs.*` names for common-derived artifacts as compatibility
|
||||||
|
behavior. They were never a public ABI.
|
||||||
|
- Do not confuse a frontend file-init fragment name with a common-derived
|
||||||
|
identity. PBS may still name its own fragments; common code must not parse
|
||||||
|
those names.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Decision: `DEC-0046`
|
||||||
|
- Plan: `PLN-0125`
|
||||||
|
- Related lessons: `LSN-0059`, `LSN-0060`
|
||||||
|
- `docs/specs/compiler/23. Compiler Pipeline Entry Points Specification.md`
|
||||||
|
- `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
|
||||||
|
- `docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md`
|
||||||
|
- `docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md`
|
||||||
|
- `docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md`
|
||||||
|
- `docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md`
|
||||||
|
- `docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md`
|
||||||
|
- `prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/models/IRLifecycleDeclaration.java`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/lifecycle/LifecycleAssemblerService.java`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/stages/AssembleLifecyclePipelineStage.java`
|
||||||
+129
@@ -0,0 +1,129 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0063
|
||||||
|
ticket: multi-frontend-validation-boundaries
|
||||||
|
title: Language vs platform validation ownership
|
||||||
|
created: 2026-09-19
|
||||||
|
tags: [compiler, compiler-general, compiler-pbs, backend, validation, multi-frontend]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Language vs platform validation ownership
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS mixed two kinds of rejection. Some failures only make sense with the
|
||||||
|
language: syntax, types, markers, barrel files, imports. Others belong to any
|
||||||
|
executable frontend: malformed `IRBackend`, invalid lifecycle declarations,
|
||||||
|
missing assembled wrappers, host-capability identity, bytecode/preload.
|
||||||
|
|
||||||
|
Without an ownership rule, the next frontend would copy PBS validators, or the
|
||||||
|
common layer would start knowing `[Init]`, barrel, and `E_SEM_*`. Spec 19 was
|
||||||
|
still titled as PBS verification, and the PBS diagnostics catalog listed
|
||||||
|
wrapper and boot-guard failures as PBS coverage.
|
||||||
|
|
||||||
|
Lifecycle assembly had already moved (`LSN-0062`). That proved the pattern. It
|
||||||
|
did not inventory the rest.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
A validation lives at the lowest layer that understands the failure without
|
||||||
|
knowing the source language.
|
||||||
|
|
||||||
|
- Language: needs AST, tokens, a language marker, a barrel, or another source
|
||||||
|
rule.
|
||||||
|
- Platform: can be checked on `IRBackend`, `IRLifecycleDeclaration`, IRVM, PBX,
|
||||||
|
host/capability tables, or ids.
|
||||||
|
|
||||||
|
The discussion published that matrix. It did not extract a generic
|
||||||
|
validator-core and did not move validators whose common contract is not closed.
|
||||||
|
|
||||||
|
Host admission is split. PBS owns the source shape of `[Host]` and
|
||||||
|
`[Capability]`. Platform owns canonical `(module, name, version)` identity and
|
||||||
|
capability consistency once those facts exist on `IRReservedMetadata`. The
|
||||||
|
current validator may stay in the PBS package until a later plan. `E_HOST_*`
|
||||||
|
is not eternal PBS semantics.
|
||||||
|
|
||||||
|
The same fact may exist on both sides with distinct identities. PBS can report
|
||||||
|
`E_SEM_MISSING_PROJECT_FRAME`; the common layer still rejects an executable
|
||||||
|
declaration with no frame root.
|
||||||
|
|
||||||
|
Platform codes are `COMMON_*`, `LOWER_IRVM_*`, or `MARSHAL_*`. PBS keeps
|
||||||
|
`E_PARSE_*`, `E_SEM_*`, `E_LINK_*`, and `E_HOST_*`. Copy origin/span when
|
||||||
|
present; a missing origin is a structural error, not a reason to invent a span.
|
||||||
|
|
||||||
|
Linking and barrel stay language-owned. `Addressable` is platform-owned and was
|
||||||
|
classified only. SDK canonical source and the broad architectural harness stay
|
||||||
|
on adjacent discussions.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
The work was editorial and test-facing.
|
||||||
|
|
||||||
|
Spec 19 is now `Compiler Verification and Safety Checks Specification`. Gates
|
||||||
|
S-U and S-I are unchanged. Section 11 states the classification rule, the
|
||||||
|
English ownership matrix, diagnostic identity, dual reporting, and the
|
||||||
|
host-admission split. It explicitly refuses validator-core extraction and
|
||||||
|
package moves.
|
||||||
|
|
||||||
|
PBS diagnostics spec 12 keeps marker, syntax, semantics, linking, and
|
||||||
|
host-attribute coverage. Common structural failures now point at spec 19
|
||||||
|
section 11 and spec 20 instead of appearing as PBS required coverage.
|
||||||
|
|
||||||
|
Spec 20 cross-references that same compiler-general ownership. The conformance
|
||||||
|
matrix added `G19-11.1` through `G19-11.6` and `PBS12-11`.
|
||||||
|
`CommonBackendArchitectureTest` now guards `backend/`, `lifecycle/`, and all
|
||||||
|
common pipeline stages. `ValidationOwnershipSpecTest` locks the title, matrix,
|
||||||
|
and PBS recut.
|
||||||
|
|
||||||
|
`PbsHostAdmissionValidator` remains under `p.studio.compiler.pbs`. No linking
|
||||||
|
or asset production code moved.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Language-owned:
|
||||||
|
|
||||||
|
- parse errors;
|
||||||
|
- `[Init]` / `[Frame]` signature and colocation;
|
||||||
|
- barrel and import failures;
|
||||||
|
- `host call not allowed during init`.
|
||||||
|
|
||||||
|
Platform-owned and already implemented:
|
||||||
|
|
||||||
|
- invalid `IRLifecycleDeclaration`;
|
||||||
|
- assembled wrapper, boot guard, and synthetic origin preconditions;
|
||||||
|
- IRVM and marshal rejection families.
|
||||||
|
|
||||||
|
Classified as platform, not moved:
|
||||||
|
|
||||||
|
- canonical host-binding identity on `IRReservedMetadata`;
|
||||||
|
- `Addressable` / asset path.
|
||||||
|
|
||||||
|
Dual reporting:
|
||||||
|
|
||||||
|
- missing `[Frame]` in PBS source is `E_SEM_MISSING_PROJECT_FRAME`;
|
||||||
|
- an executable declaration without frame root is a common structural error.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- Do not treat “classified as platform” as “move the class now.” Host admission
|
||||||
|
still waits on the SDK source discussion.
|
||||||
|
- Do not merge language and platform failures into one hybrid code. Two
|
||||||
|
identities are cheaper than a lost message.
|
||||||
|
- Do not put PBS governance or PBS diagnostics in charge of compiler-general
|
||||||
|
safety gates.
|
||||||
|
- Do not scan PBS frontend sources with the platform architecture guard. The
|
||||||
|
guard is for common validators, not for the language package that must remain.
|
||||||
|
- Do not invent a validator-core because several common checks exist. They
|
||||||
|
already live on their stages.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Decision: `DEC-0047`
|
||||||
|
- Plan: `PLN-0126`
|
||||||
|
- Related lesson: `LSN-0062` - Common lifecycle assembly after frontend declaration
|
||||||
|
- Related lesson: `LSN-0059` - Common IRBackend handoff and backend guardrails
|
||||||
|
- `docs/specs/compiler/19. Verification and Safety Checks Specification.md`
|
||||||
|
- `docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md`
|
||||||
|
- `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
|
||||||
|
- `docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/specs/ValidationOwnershipSpecTest.java`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/specs/CommonBackendArchitectureTest.java`
|
||||||
+121
@@ -0,0 +1,121 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0064
|
||||||
|
ticket: multi-frontend-sdk-canonical-definition
|
||||||
|
title: Runtime owns console ABI; PBS is delivery
|
||||||
|
created: 2026-09-19
|
||||||
|
tags: [compiler, compiler-general, sdk, stdlib, hostcalls, intrinsics, multi-frontend]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Runtime owns console ABI; PBS is delivery
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
"SDK" mixed three layers: platform ABI, PBS stdlib shells, and docs. The PBS
|
||||||
|
compiler reads `[Host]` and `[IntrinsicCall]` from `.pbs` files. It does not
|
||||||
|
read the runtime registry. Intrinsics already had a CSV in the runtime
|
||||||
|
repository, a handwritten Java enum, and a disabled parity test. Spec 8
|
||||||
|
documented `audio` and `@core:math`. Disk had `game/stdlib/1` with `color`,
|
||||||
|
`asset`, `composer`, `gfx`, `input`, and `log`. Spec 18 preferred `@sdk:*` for
|
||||||
|
host APIs while `@sdk:input` was a builtin.
|
||||||
|
|
||||||
|
There is no second language in this phase. The risk was not a missing generic
|
||||||
|
SDK. The risk was treating PBS shells, or a stale spec, as console ABI.
|
||||||
|
DEC-0047 had already classified canonical host identity as platform-owned and
|
||||||
|
left `PbsHostAdmissionValidator` in the PBS package until a shared source
|
||||||
|
existed.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
This discussion was an audit. It published an authority map. It did not create
|
||||||
|
a canonical schema, generate bindings, enable intrinsic parity, or move the
|
||||||
|
host-admission validator.
|
||||||
|
|
||||||
|
The console has two distinct axes:
|
||||||
|
|
||||||
|
- VM-owned intrinsics, identity `canonical_name@version` plus `final_id`;
|
||||||
|
- host-backed calls, identity `(module, name, version)` plus capability.
|
||||||
|
|
||||||
|
Do not unify those axes into one catalog while PBS is the only frontend.
|
||||||
|
|
||||||
|
Conflict resolution:
|
||||||
|
|
||||||
|
- Intrinsic conflict: `runtime/docs/vm-arch/INTRINSICS.csv` wins. Studio
|
||||||
|
`docs/vm-arch/INTRINSICS.csv` is a mirror. `IRVMIntrinsicDefinition` is
|
||||||
|
derived. PBS `[BuiltinType]` / `[IntrinsicCall]` shells are delivery.
|
||||||
|
- Host conflict: runtime spec 16 and `SyscallMeta` win. PBS `[Host]` attributes
|
||||||
|
must not define ABI. They declare the shell the PBS compiler reads today.
|
||||||
|
|
||||||
|
`@sdk:*` / `@core:*` paths must not imply ownership. `@sdk:input` is a
|
||||||
|
registered builtin exception. It was not moved to `@core`.
|
||||||
|
|
||||||
|
PBS conformance means PBS shells and docs match runtime ABI, not the reverse.
|
||||||
|
`PbsHostAdmissionValidator` may stay in the PBS package. `E_HOST_*` is not
|
||||||
|
eternal PBS semantics.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
The work was editorial and test-facing.
|
||||||
|
|
||||||
|
Spec 18 now states that PBS stdlib is delivery and must not define syscall IDs,
|
||||||
|
intrinsic `final_id` values, or `SyscallMeta`. Runtime catalogs outrank it.
|
||||||
|
`@sdk:input` is recorded as the current builtin exception.
|
||||||
|
|
||||||
|
Spec 8 now documents `<target>/stdlib/<N>/...` with current line `1` at
|
||||||
|
`game/stdlib/1`: `core/color` and `sdk/{asset,composer,gfx,input,log}`. It no
|
||||||
|
longer ships `audio` or `@core:math` as current modules.
|
||||||
|
|
||||||
|
Spec 6.2 now requires PBS host shells to repeat the runtime registry and forbids
|
||||||
|
inventing `(module, name, version)`. The authority example is
|
||||||
|
`("gfx2d", "clear", 1)`.
|
||||||
|
|
||||||
|
`ConsoleAbiAuthoritySpecTest` locks those sentences. No production compiler
|
||||||
|
code, stdlib `.pbs`, or validator package moved. The intrinsic parity test
|
||||||
|
stays disabled.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Runtime wins:
|
||||||
|
|
||||||
|
- `color.rgb@1` / `final_id` `0x1101` come from `INTRINSICS.csv`;
|
||||||
|
- `("gfx2d", "clear", 1)` and `("asset", "load", 1)` come from `SyscallMeta`.
|
||||||
|
|
||||||
|
PBS delivers, and does not own, those identities:
|
||||||
|
|
||||||
|
- `@core:color` with `[BuiltinType(name = "color", version = 1)]`;
|
||||||
|
- `@sdk:gfx` `LowGfx.clear` with `[Host(module = "gfx2d", name = "clear", version = 1)]`;
|
||||||
|
- `@sdk:input` with `[BuiltinType]` / `[IntrinsicCall]` under `@sdk`.
|
||||||
|
|
||||||
|
Stale docs that the recut removed as current line-1 inventory:
|
||||||
|
|
||||||
|
- `stdlib/1/sdk/audio`;
|
||||||
|
- `@core:math` as a packaged module.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- Do not treat PBS stdlib as the ABI catalog because the compiler already reads
|
||||||
|
it. That is convenience, not authority.
|
||||||
|
- Do not create `HOSTCALLS.csv` or generate the Java enum because the map now
|
||||||
|
exists. A catalog waits on a second consumer.
|
||||||
|
- Do not move `PbsHostAdmissionValidator` on the strength of this map. DEC-0047
|
||||||
|
classified identity as platform; this discussion published who wins; the
|
||||||
|
validator still has no shared catalog to consume.
|
||||||
|
- Do not read `@sdk` as host and `@core` as VM. Path is packaging. `@sdk:input`
|
||||||
|
is builtin.
|
||||||
|
- Do not enable `IRVMIntrinsicRegistryParityTest` as a side effect of a doc
|
||||||
|
recut. That is compiler/runtime sync, not PBS packaging conformance.
|
||||||
|
- Do not put the authority map only in a decision. Housekeep deletes workflow
|
||||||
|
artifacts. Specs and this lesson keep the map.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Decision: `DEC-0048`
|
||||||
|
- Plan: `PLN-0127`
|
||||||
|
- Related lesson: `LSN-0063` - Language vs platform validation ownership
|
||||||
|
- Related lesson: `LSN-0061` - PBX is the language-neutral runtime boundary
|
||||||
|
- `docs/specs/compiler/18. Standard Library Surface Specification.md`
|
||||||
|
- `docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md`
|
||||||
|
- `docs/specs/compiler-languages/pbs/6.2. Host ABI Binding and Loader Resolution Specification.md`
|
||||||
|
- `docs/vm-arch/README.md`
|
||||||
|
- `../runtime/docs/vm-arch/INTRINSICS.csv`
|
||||||
|
- `../runtime/docs/specs/runtime/16-host-abi-and-syscalls.md`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/specs/ConsoleAbiAuthoritySpecTest.java`
|
||||||
+136
@@ -0,0 +1,136 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0061
|
||||||
|
ticket: multi-frontend-pvm-neutrality
|
||||||
|
title: PBX is the language-neutral runtime boundary
|
||||||
|
created: 2026-09-18
|
||||||
|
tags: [vm-arch, runtime, pvm, pbx, compiler, multi-frontend]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBX is the language-neutral runtime boundary
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
PBS was the first implemented frontend, so its name still appeared in a few
|
||||||
|
common compiler specification titles. That editorial residue made it easier to
|
||||||
|
misread the architecture as if PBS owned bytecode, IRVM, or the PVM execution
|
||||||
|
model.
|
||||||
|
|
||||||
|
The implementation was already mostly neutral: the compiler emitted PBX, the
|
||||||
|
runtime loaded PBX, and the common backend did not import PBS frontend packages.
|
||||||
|
The real risk was future drift. In particular, IRVM could be mistaken for a
|
||||||
|
runtime input, `PBS\0` could be confused with the executable magic, and duplicated
|
||||||
|
VM-architecture documents could silently become competing authorities.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
The executable pipeline is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
language frontend -> IRBackend -> IRVM -> PBX -> loader/verifier -> PVM
|
||||||
|
```
|
||||||
|
|
||||||
|
`IRBackend`, `IRVM`, optimization, and PBX emission are compiler-owned.
|
||||||
|
`IRVM` is an internal compiler representation and never crosses the runtime
|
||||||
|
boundary. PBX is the only executable artifact consumed by the runtime.
|
||||||
|
|
||||||
|
The runtime repository owns PBX binary layout, Core ISA, loader behavior,
|
||||||
|
verification, and PVM execution. Studio owns the common compiler transformations
|
||||||
|
that produce conforming PBX. Studio copies of VM-architecture documents are
|
||||||
|
mirrors, not independent authorities.
|
||||||
|
|
||||||
|
`PBS` names a language, frontend, stdlib, and explicitly language-specific
|
||||||
|
integration. It does not name the executable format, magic, ISA, ABI, program
|
||||||
|
image, or runtime type. The canonical persisted artifact is `program.pbx`, and
|
||||||
|
its binary magic is `PBX\0`.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
The common compiler specifications now identify bytecode/PBX and IRVM
|
||||||
|
optimization as language-neutral surfaces. They explicitly state that IRVM is
|
||||||
|
internal to the compiler and that PBX is the compiler/runtime boundary. Existing
|
||||||
|
PBS references were retained where they describe legitimate frontend-specific
|
||||||
|
publication or metadata behavior.
|
||||||
|
|
||||||
|
Studio's copies of `ARCHITECTURE.md`, `ISA_CORE.md`, and `INTRINSICS.csv` were
|
||||||
|
synchronized with the runtime repository. A mirror policy now identifies the
|
||||||
|
runtime repository as canonical and provides byte-for-byte comparison commands.
|
||||||
|
|
||||||
|
Existing Studio tests already proved two important invariants:
|
||||||
|
|
||||||
|
- `BytecodeModule` serializes the exact `PBX\0` header;
|
||||||
|
- common backend contracts neither import nor publicly expose PBS frontend
|
||||||
|
types.
|
||||||
|
|
||||||
|
Runtime conformance was strengthened in three focused places:
|
||||||
|
|
||||||
|
- the bytecode invalid-magic regression now explicitly proves that legacy
|
||||||
|
`PBS\0` is rejected;
|
||||||
|
- the PVM initialization regression now creates a `BytecodeModule` directly,
|
||||||
|
serializes it, loads and verifies it, prepares the boot call, and executes it
|
||||||
|
through `HALT` without any frontend;
|
||||||
|
- a quality check inspects the `prometeu-bytecode` and `prometeu-vm` manifests
|
||||||
|
and rejects dependencies whose identities belong to compiler or frontend
|
||||||
|
layers.
|
||||||
|
|
||||||
|
No production VM behavior, ISA, ABI, or binary format changed.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Language-specific work stops before the common backend:
|
||||||
|
|
||||||
|
```text
|
||||||
|
PBS AST and semantic model
|
||||||
|
-> PBS lowering
|
||||||
|
-> neutral IRBackend data
|
||||||
|
-> common IRVM lowering and optimization
|
||||||
|
-> PBX\0
|
||||||
|
```
|
||||||
|
|
||||||
|
A future frontend follows the same boundary:
|
||||||
|
|
||||||
|
```text
|
||||||
|
FutureLanguage AST and semantic model
|
||||||
|
-> FutureLanguage lowering
|
||||||
|
-> neutral IRBackend data
|
||||||
|
-> the same common IRVM and PBX stages
|
||||||
|
```
|
||||||
|
|
||||||
|
The runtime sees the same PBX contract in both cases. It does not receive a
|
||||||
|
`languageId`, source extension, AST object, IRVM object, or frontend service.
|
||||||
|
|
||||||
|
## Pitfalls and Anti-Patterns
|
||||||
|
|
||||||
|
- Do not expose IRVM as a convenient runtime protocol. It is optimized for
|
||||||
|
compiler transformations, not binary compatibility or runtime loading.
|
||||||
|
- Do not rename PBX concepts after the first frontend. `PBS\0` is invalid even
|
||||||
|
when PBS produced the program.
|
||||||
|
- Do not globally ban the word `PBS` from runtime documentation. PBS is a valid
|
||||||
|
guest-language example; guards should inspect dependencies, public types, and
|
||||||
|
format identities instead of raw text.
|
||||||
|
- Do not duplicate tests when an existing guard proves the entire invariant.
|
||||||
|
Extend coverage only for the missing distinction, such as explicit `PBS\0`
|
||||||
|
rejection.
|
||||||
|
- Do not let a documentation mirror become a second authority. Synchronize it
|
||||||
|
against runtime or replace it with an explicit reference.
|
||||||
|
- Loading a PBX image is not the same as beginning execution. The PVM boot test
|
||||||
|
must prepare the published boot call before running the instruction budget.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- `docs/specs/compiler/15. Bytecode and PBX Mapping Specification.md`
|
||||||
|
- `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
|
||||||
|
- `docs/specs/compiler/21. IRVM Optimization Pipeline Specification.md`
|
||||||
|
- `docs/vm-arch/README.md`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/bytecode/BytecodeModule.java`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/specs/CommonBackendArchitectureTest.java`
|
||||||
|
- Runtime: `crates/console/prometeu-bytecode/src/model.rs`
|
||||||
|
- Runtime: `crates/console/prometeu-vm/src/virtual_machine.rs`
|
||||||
|
- Runtime: `crates/dev/prometeu-quality-checks/tests/pvm_frontend_neutrality.rs`
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- PBX is the stable, language-neutral executable boundary.
|
||||||
|
- IRVM stays private to the compiler pipeline.
|
||||||
|
- Runtime authority and compiler authority are complementary, not competing.
|
||||||
|
- Small dependency and artifact tests are enough to protect this boundary
|
||||||
|
without introducing a plugin platform or a second language.
|
||||||
+148
@@ -0,0 +1,148 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0065
|
||||||
|
ticket: multi-frontend-synthetic-test-frontend
|
||||||
|
title: Synthetic test frontend proves common pipeline neutrality
|
||||||
|
created: 2026-09-19
|
||||||
|
tags: [compiler, compiler-general, frontend, tests, backend, multi-frontend]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Synthetic test frontend proves common pipeline neutrality
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
The common pipeline already had `FrontendProvider`, `IRBackend` as the
|
||||||
|
executable handoff, common lifecycle assembly, and `IRBackend -> IRVM -> PBX`.
|
||||||
|
Direct construction tests proved the backend could lower a handmade
|
||||||
|
`IRBackend`. Import guards proved common backend code did not depend on PBS
|
||||||
|
packages.
|
||||||
|
|
||||||
|
That was not enough. Nothing proved that a second provider, resolved by
|
||||||
|
`languageId`, could enter through `DiscoverPhase` and
|
||||||
|
`FrontendPhasePipelineStage`, assemble lifecycle, and finish
|
||||||
|
`BuilderPipelineService.compile()` at verified bytecode without instantiating
|
||||||
|
PBS, reading `.pbs` files, or loading PBS stdlib.
|
||||||
|
|
||||||
|
`CompileOnlyFrontendProvider` already existed as a local test double. It was
|
||||||
|
not registered, returned an empty `IRBackend`, and never called the pipeline.
|
||||||
|
It did not close this gap.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
Pipeline neutrality is proved by a **test-only** compile-only
|
||||||
|
`FrontendProvider`, not by a second product language and not by injecting IR
|
||||||
|
into compile stages.
|
||||||
|
|
||||||
|
Locked shape (former Option A):
|
||||||
|
|
||||||
|
- `languageId` is `synth`.
|
||||||
|
- The provider and `FrontendPhaseService` live only in
|
||||||
|
`prometeu-build-pipeline` test sources.
|
||||||
|
- `languageService()` is empty. There is no parser, grammar, semantic
|
||||||
|
presentation, or stdlib catalog.
|
||||||
|
- `sourceRoots` is `src`. `allowedExtensions` must not collide with `pbs` /
|
||||||
|
`barrel`. The fixture must **not** create a source file of that extension.
|
||||||
|
An empty `src/` directory must still exist because `WireProjectsPhase`
|
||||||
|
resolves `toRealPath()`.
|
||||||
|
- The compiler ignores source text and emits one module, one `frame` body
|
||||||
|
that is a single `RET`, and an `IRLifecycleDeclaration` with exactly one
|
||||||
|
`FRAME_ROOT` whose origin span is filled.
|
||||||
|
- The handoff must not declare `FILE_INIT_FRAGMENT` or `PROJECT_INIT`, and
|
||||||
|
must not pre-materialize wrappers, module-init, or `BOOT_GUARD`. The common
|
||||||
|
assembler produces `__prometeu.lifecycle.frame_wrapper$mN` and the boot
|
||||||
|
guard.
|
||||||
|
- The IR must not contain host bindings, capabilities, intrinsics, PBS types,
|
||||||
|
PBS stdlib, or `__pbs.` names.
|
||||||
|
|
||||||
|
The acceptance path is `compile()` through `VerifyBytecode`. Writing
|
||||||
|
`program.pbx` is not the criterion. `build()` only adds disk I/O.
|
||||||
|
|
||||||
|
Registration stays on the existing static `FrontendRegistryService`.
|
||||||
|
`register` and `unregister` are public. `unregister` refuses to remove the
|
||||||
|
default PBS provider and is a no-op for unknown ids. Tests register `synth`
|
||||||
|
for the duration of the run and unregister in `try/finally`.
|
||||||
|
`bootstrapDefaults()`, `AppContainer`, and the Studio language catalog must
|
||||||
|
not register `synth`.
|
||||||
|
|
||||||
|
Do not inject a `Registry` into the pipeline, add a `frontends/synth` module,
|
||||||
|
scan the classpath, or treat a dummy on-disk extension as a language. Do not
|
||||||
|
replace `LifecycleAssemblerServiceTest`, `LowerToIRVMServiceTest`, or
|
||||||
|
`IRBackendExecutableContractTest` with this fixture.
|
||||||
|
|
||||||
|
A blank `prometeu.json` `language` field still defaults to PBS. The synthetic
|
||||||
|
project must set `language: synth` explicitly.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
`FrontendRegistryService.register(FrontendProvider)` is the explicit
|
||||||
|
registration API. `unregister(String languageId)` removes a non-PBS provider
|
||||||
|
or no-ops if the id is absent. Duplicate `register` still fails.
|
||||||
|
`bootstrapDefaults()` still registers only PBS.
|
||||||
|
|
||||||
|
The test fixture is:
|
||||||
|
|
||||||
|
- `p.studio.compiler.synth.SyntheticFrontendProvider`
|
||||||
|
- `p.studio.compiler.synth.SyntheticFrontendPhaseService`
|
||||||
|
|
||||||
|
`SyntheticFrontendPipelineTest` writes a temporary project
|
||||||
|
(`language: synth`, `target: Game`, numeric `stdlib`, empty `src/`),
|
||||||
|
registers the provider, calls `BuilderPipelineService.compile()`, and
|
||||||
|
asserts:
|
||||||
|
|
||||||
|
- the synthetic compiler ran;
|
||||||
|
- resolved `languageId` is `synth`, not `pbs`;
|
||||||
|
- diagnostics have no errors;
|
||||||
|
- in-memory bytecode is non-empty and verified;
|
||||||
|
- assembled entrypoint is `__prometeu.lifecycle.frame_wrapper$m0`;
|
||||||
|
- a hidden boot guard is present;
|
||||||
|
- no `__pbs.` names;
|
||||||
|
- no `.pbs` / `.barrel` sources were required;
|
||||||
|
- after `unregister`, `listProviders()` is PBS-only.
|
||||||
|
|
||||||
|
Spec 23 section 8.3 records that a compile-only registered provider is a
|
||||||
|
valid pipeline participant and that the common pipeline must not require PBS
|
||||||
|
types, PBS sources, or PBS stdlib to emit verified bytecode. Spec 22 row
|
||||||
|
`G23-8.3` binds that obligation to the synthetic pipeline test.
|
||||||
|
|
||||||
|
PBS production code, Studio, and `AppContainer` were not changed.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Good:
|
||||||
|
|
||||||
|
- register `synth`, compile a temp project with empty `src/`, unregister;
|
||||||
|
- `FRAME_ROOT` with `FileId(0)` and a non-none span, even with no source file
|
||||||
|
in `FileTable`;
|
||||||
|
- assert the synthetic compiler was invoked instead of importing
|
||||||
|
`PBSFrontendPhaseService` from build-pipeline tests.
|
||||||
|
|
||||||
|
Bad:
|
||||||
|
|
||||||
|
- omitting `language` in the manifest so discovery silently uses PBS;
|
||||||
|
- creating `main.dummy` and calling that a second frontend;
|
||||||
|
- putting the provider under `prometeu-compiler/frontends/`;
|
||||||
|
- leaving `synth` registered after the test so later tests see two providers;
|
||||||
|
- using this pipeline test as a substitute for assembler or IRVM unit tests.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- `WireProjectsPhase` still needs `src/` on disk. Empty is not the same as
|
||||||
|
missing.
|
||||||
|
- Origin span `Span.none()` is rejected by the assembler. Use a real
|
||||||
|
`FileId` even when no file was loaded.
|
||||||
|
- `unregister("pbs")` must fail. A cleanup path that blindly unregisters the
|
||||||
|
resolved language would delete the product default.
|
||||||
|
- `listProviders()` feeds the Studio catalog. A leaked test registration
|
||||||
|
would show `synth` as a new-project language.
|
||||||
|
- Direct `IRBackend` construction tests still own backend-only proofs. The
|
||||||
|
synthetic frontend owns the registry-plus-pipeline proof. Keep both.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Decision: `DEC-0049`
|
||||||
|
- Plan: `PLN-0128`
|
||||||
|
- Related lessons: `LSN-0055`, `LSN-0056`, `LSN-0059`, `LSN-0062`, `LSN-0061`
|
||||||
|
- `docs/specs/compiler/23. Compiler Pipeline Entry Points Specification.md`
|
||||||
|
- `docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md`
|
||||||
|
- `prometeu-compiler/prometeu-frontend-registry/src/main/java/p/studio/compiler/FrontendRegistryService.java`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/synth/SyntheticFrontendProvider.java`
|
||||||
|
- `prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/integration/SyntheticFrontendPipelineTest.java`
|
||||||
+151
@@ -0,0 +1,151 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0066
|
||||||
|
ticket: multi-frontend-architectural-tests
|
||||||
|
title: ArchUnit guards Java multi-frontend boundaries
|
||||||
|
created: 2026-09-19
|
||||||
|
tags: [compiler, compiler-general, studio, frontend, architecture, tests, multi-frontend]
|
||||||
|
---
|
||||||
|
|
||||||
|
# ArchUnit guards Java multi-frontend boundaries
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
The multi-frontend boundaries already existed in specs and lessons: common
|
||||||
|
code selects a frontend by `languageId`, `IRBackend` is language-neutral,
|
||||||
|
lifecycle assembly is common, and PBS is one provider. The automated
|
||||||
|
protection did not match that model.
|
||||||
|
|
||||||
|
The old guards walked Java source and searched for substrings:
|
||||||
|
|
||||||
|
- `import p.studio.compiler.pbs`
|
||||||
|
- `new PBSFrontendPhaseService(`
|
||||||
|
- `new PbsEditorialSupportService(`
|
||||||
|
|
||||||
|
Those checks missed field, signature, and constructor coupling. They also
|
||||||
|
treated `p.studio.compiler.pbs` as the whole PBS surface. Facades such as
|
||||||
|
`PBSFrontendProvider`, `PBSDefinitions`, and `PBSFrontendPhaseService` live
|
||||||
|
in the PBS module but not in that package. `prometeu-app` and
|
||||||
|
`prometeu-lsp-v1` declared an `implementation` dependency on PBS without
|
||||||
|
importing any PBS type.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
Java multi-frontend boundaries are enforced by **ArchUnit + JUnit 5**, not by
|
||||||
|
source substring search, except for the `__pbs.` literal scan that bytecode
|
||||||
|
cannot see.
|
||||||
|
|
||||||
|
Durable locks from DEC-0050:
|
||||||
|
|
||||||
|
- ArchUnit is test-only, pinned in `gradle/libs.versions.toml`.
|
||||||
|
- Rules live in the test-only Gradle project `:prometeu-architecture-tests`.
|
||||||
|
That project has no production sources. It is not a plugin loader.
|
||||||
|
- A PBS type is a class whose bytecode originates from
|
||||||
|
`:prometeu-compiler:frontends:prometeu-frontend-pbs`. Package
|
||||||
|
`p.studio.compiler.pbs` is not the complete boundary. Name prefixes
|
||||||
|
`PBS*` / `Pbs*` are not the identity.
|
||||||
|
- Production may depend on PBS types only in:
|
||||||
|
- the PBS module itself;
|
||||||
|
- `prometeu-frontend-registry` / `FrontendRegistryService`, and only on
|
||||||
|
`PBSFrontendProvider` and `PBSDefinitions`.
|
||||||
|
- `AppContainer` is not a PBS composition root. It may call
|
||||||
|
`FrontendRegistryService.bootstrapDefaults()`. It must not instantiate PBS
|
||||||
|
types.
|
||||||
|
- `synth` is not in the production allowlist and must not be registered in
|
||||||
|
`bootstrapDefaults()`.
|
||||||
|
- Runtime, PVM, and the Rust repository stay out of this discussion
|
||||||
|
(LSN-0061).
|
||||||
|
- `IRBackendExecutableContractTest` remains the public-contract shape audit.
|
||||||
|
ArchUnit covers module-origin dependence.
|
||||||
|
|
||||||
|
Do not migrate PBS facades into another package just to make the test
|
||||||
|
easier. Do not ban the word `PBS` in docs, fixtures, or comments.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
`:prometeu-architecture-tests` imports production classes under `p.studio`
|
||||||
|
with `ImportOption.DoNotIncludeTests` and applies three ArchUnit rules:
|
||||||
|
|
||||||
|
1. classes outside the PBS module and the registry must not depend on
|
||||||
|
PBS-module types;
|
||||||
|
2. registry production may depend only on `PBSFrontendProvider` and
|
||||||
|
`PBSDefinitions` from that module;
|
||||||
|
3. frontend-api `p.studio.compiler.models` must not depend on PBS-module
|
||||||
|
types.
|
||||||
|
|
||||||
|
A separate JUnit test walks `build.gradle.kts` files and allows the PBS
|
||||||
|
project dependency only for:
|
||||||
|
|
||||||
|
- `:prometeu-compiler:prometeu-frontend-registry` as `implementation`/`api`;
|
||||||
|
- `:prometeu-architecture-tests` as `testImplementation` (needed to classify
|
||||||
|
class origin).
|
||||||
|
|
||||||
|
The `__pbs.` source scan moved to
|
||||||
|
`CommonBackendPbsPrefixScanTest` and still covers `backend/`, `lifecycle/`,
|
||||||
|
and `workspaces/stages/`.
|
||||||
|
|
||||||
|
Gradle graph cleanup:
|
||||||
|
|
||||||
|
- `prometeu-app` and `prometeu-lsp-v1` no longer `implementation` PBS.
|
||||||
|
Runtime classloading of `PBSFrontendProvider` still comes through the
|
||||||
|
registry's implementation dependency.
|
||||||
|
- `prometeu-studio` no longer `testImplementation` PBS. No studio test
|
||||||
|
compiled against PBS types.
|
||||||
|
|
||||||
|
Source-walk import/constructor tests were deleted.
|
||||||
|
`FrontendProviderBoundaryTest` keeps only
|
||||||
|
`compileOnlyFrontendProviderMayOmitLanguageService`.
|
||||||
|
|
||||||
|
Specs 19 §11 and 20 now say common/platform code must not depend on types
|
||||||
|
from the PBS frontend module. Matrix rows G19-11.6, G20-4.1.2, and G20-4.3.3
|
||||||
|
point at the ArchUnit rules and the `__pbs.` scan.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Good:
|
||||||
|
|
||||||
|
- ArchUnit failure names the class that depends on a PBS-module type,
|
||||||
|
including a facade in package `p.studio.compiler`.
|
||||||
|
- Registry `bootstrapDefaults()` constructs `PBSFrontendProvider`. That is
|
||||||
|
the allowed composition root.
|
||||||
|
- App calls `FrontendRegistryService.bootstrapDefaults()` and has no PBS
|
||||||
|
project dependency.
|
||||||
|
|
||||||
|
Bad:
|
||||||
|
|
||||||
|
- Searching source for `import p.studio.compiler.pbs` and calling the
|
||||||
|
boundary protected.
|
||||||
|
- Treating `AppContainer` as the place that may `new PBSFrontendProvider()`.
|
||||||
|
- Identifying PBS by class name prefix, so a future `PbsLike` helper in
|
||||||
|
common code is banned or a PBS facade is missed.
|
||||||
|
- Adding ArchUnit to `java-common-conventions` for every module.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- Same Java package does not mean same Gradle module.
|
||||||
|
`FrontendRegistryService` and `PBSFrontendProvider` both sit in
|
||||||
|
`p.studio.compiler`. Origin is the module path or JAR name.
|
||||||
|
- `@AnalyzeClasses` classes must not mix `@ArchTest` and Jupiter `@Test` on
|
||||||
|
the same class. The ArchUnit engine owns `@ArchTest`.
|
||||||
|
- `DoNotIncludeTests` is required. The architecture-test sources themselves
|
||||||
|
reference PBS types in order to name the allowlist.
|
||||||
|
- Removing PBS from app/lsp compile classpath is safe only because registry
|
||||||
|
still `implementation`s PBS, which is runtime-transitive.
|
||||||
|
- `testImplementation` of PBS on studio is not a production leak, but if no
|
||||||
|
studio test needs PBS types it is still a lying graph. The allowlist test
|
||||||
|
rejects it.
|
||||||
|
- Do not point ArchUnit at the Rust runtime. `__pbs.` in Java source is a
|
||||||
|
string contract, not a type dependency.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Decision: `DEC-0050`
|
||||||
|
- Plan: `PLN-0129`
|
||||||
|
- Related lessons: `LSN-0055`, `LSN-0059`, `LSN-0062`, `LSN-0063`,
|
||||||
|
`LSN-0061`, `LSN-0065`
|
||||||
|
- `docs/specs/compiler/19. Verification and Safety Checks Specification.md`
|
||||||
|
- `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
|
||||||
|
- `docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md`
|
||||||
|
- `prometeu-architecture-tests/src/test/java/p/studio/architecture/PbsModuleBoundaryArchTest.java`
|
||||||
|
- `prometeu-architecture-tests/src/test/java/p/studio/architecture/PbsGradleDependencyAllowlistTest.java`
|
||||||
|
- `prometeu-compiler/prometeu-frontend-registry/src/main/java/p/studio/compiler/FrontendRegistryService.java`
|
||||||
|
- `prometeu-compiler/prometeu-frontend-api/src/test/java/p/studio/compiler/models/IRBackendExecutableContractTest.java`
|
||||||
+167
@@ -0,0 +1,167 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0067
|
||||||
|
ticket: multi-frontend-avoid-premature-abstractions
|
||||||
|
title: Multi-frontend phase rejects premature infrastructure
|
||||||
|
created: 2026-09-19
|
||||||
|
tags: [compiler, compiler-general, studio, frontend, architecture, multi-frontend, simplicity]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Multi-frontend phase rejects premature infrastructure
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
The multi-frontend preparation needed a standing simplicity rule. The original
|
||||||
|
agenda asked for that rule *before* the other multi-frontend discussions.
|
||||||
|
Those discussions already closed (DSC-0054 through DSC-0064). The remaining
|
||||||
|
risk was not a missing plugin platform.
|
||||||
|
|
||||||
|
The remaining risk was twofold:
|
||||||
|
|
||||||
|
1. using "keep it simple" to put PBS construction back into common compiler,
|
||||||
|
Studio, LSP, or app code;
|
||||||
|
2. inventing marketplace, JAR loading, RPC, validator-core, or a generic SPI
|
||||||
|
"for a future language" that does not exist in this repository.
|
||||||
|
|
||||||
|
`FrontendRegistryService` is a static singleton. The original agenda listed
|
||||||
|
a global service locator as out of scope. Without an explicit exception, a
|
||||||
|
later change could inject a `Registry` into the pipeline for purity, which
|
||||||
|
DSC-0063 already refused.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
This is standing policy for *future* work in the current phase: PBS as the
|
||||||
|
only product frontend, `synth` as a test-only provider, frontends in-repo.
|
||||||
|
It is not an audit of closed discussions and must not rewrite them.
|
||||||
|
|
||||||
|
Durable locks from DEC-0051:
|
||||||
|
|
||||||
|
- Implementation of this discussion is the decision plus this lesson. There
|
||||||
|
is no new spec, no new ArchUnit rule, and no production refactor.
|
||||||
|
- Spec 23 §2 and §8.3 remain the discovery MUST NOT surface. Do not copy
|
||||||
|
those sentences into a new spec.
|
||||||
|
- Architectural tests stay owned by LSN-0066.
|
||||||
|
|
||||||
|
### Static registry is allowed
|
||||||
|
|
||||||
|
`FrontendRegistryService` as a static singleton, with public `register` and
|
||||||
|
`unregister` and `bootstrapDefaults()` registering only PBS, is the
|
||||||
|
composition mechanism of this phase. Treat that as an explicit exception,
|
||||||
|
not as a banned service locator.
|
||||||
|
|
||||||
|
Discovery must not use `ServiceLoader`, classpath scanning, reflection-based
|
||||||
|
discovery, an external JAR, or runtime plugin installation.
|
||||||
|
|
||||||
|
Do not inject a `Registry` into the pipeline, LSP, or `AppContainer`.
|
||||||
|
`AppContainer` is not a PBS composition root. It may call
|
||||||
|
`FrontendRegistryService.bootstrapDefaults()`. It must not instantiate PBS
|
||||||
|
types.
|
||||||
|
|
||||||
|
### Real in-repo consumer
|
||||||
|
|
||||||
|
A new interface, module, SPI, generator, or framework is allowed only when
|
||||||
|
a real in-repo consumer exists. In this phase that consumer is one of:
|
||||||
|
|
||||||
|
- the PBS product frontend;
|
||||||
|
- the `synth` test frontend;
|
||||||
|
- a second product frontend accepted by its own decision.
|
||||||
|
|
||||||
|
"For a future language", "for the marketplace", or "when we have plugins"
|
||||||
|
is not a consumer.
|
||||||
|
|
||||||
|
`FrontendProvider`, `IRBackend`, common lifecycle assembly, and test-only
|
||||||
|
ArchUnit are not premature. They already have consumers.
|
||||||
|
|
||||||
|
### Forbidden in this phase
|
||||||
|
|
||||||
|
Until a later decision authorizes it with a real consumer, do not introduce:
|
||||||
|
|
||||||
|
1. dynamic frontend discovery (plugin, `ServiceLoader`, scan, external JAR,
|
||||||
|
runtime install);
|
||||||
|
2. RPC, sockets, a process supervisor, or version negotiation between
|
||||||
|
compiler and frontend;
|
||||||
|
3. a marketplace, hot reload, or frontend sandbox;
|
||||||
|
4. a validator-core or generic validation framework;
|
||||||
|
5. an SDK schema/generator or `HOSTCALLS.csv` as canonical ABI (LSN-0064);
|
||||||
|
6. a product module `frontends/synth`;
|
||||||
|
7. an injected `Registry`, or `AppContainer` as the PBS composition root.
|
||||||
|
|
||||||
|
This list is not a monorepo-wide simplicity charter. It does not govern
|
||||||
|
JavaFX, packer, or LSP protocol design. Owner is `compiler/general`, with
|
||||||
|
impact on `studio` on the multi-frontend axis.
|
||||||
|
|
||||||
|
### Neighbors stay closed
|
||||||
|
|
||||||
|
Do not reinterpret, relax, "simplify", or reimplement:
|
||||||
|
|
||||||
|
- provider/registry (LSN-0055 / spec 23 §8.3);
|
||||||
|
- common lifecycle;
|
||||||
|
- console ABI / PBS delivery;
|
||||||
|
- `synth`;
|
||||||
|
- ArchUnit / PBS module identity.
|
||||||
|
|
||||||
|
Using this policy to keep `new PBSFrontendPhaseService()` (or equivalent)
|
||||||
|
in common code is refused. That is PBS recoupling, not simplicity.
|
||||||
|
|
||||||
|
A second product frontend needs its own decision. This lesson neither
|
||||||
|
replaces that decision nor blocks it.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
No production Java, Gradle, spec, or ArchUnit file changed.
|
||||||
|
|
||||||
|
The map above is the implementation. Future compiler/studio plans on this
|
||||||
|
axis should cite it when they propose a new module, SPI, or discovery
|
||||||
|
mechanism.
|
||||||
|
|
||||||
|
Code that already matches the phase:
|
||||||
|
|
||||||
|
- `FrontendProvider` exposes `specification()`, `compiler()`, and optional
|
||||||
|
`languageService()`;
|
||||||
|
- `FrontendRegistryService.bootstrapDefaults()` registers PBS only;
|
||||||
|
- `AppContainer` only calls that bootstrap;
|
||||||
|
- `synth` lives in build-pipeline test sources;
|
||||||
|
- ArchUnit lives in `:prometeu-architecture-tests`.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
Good:
|
||||||
|
|
||||||
|
- add a method to `FrontendProvider` because PBS or `synth` cannot compile
|
||||||
|
or register without it;
|
||||||
|
- keep `unregister` on the static registry so `synth` tests can clean up;
|
||||||
|
- reject a proposal to load language JARs from a plugin directory.
|
||||||
|
|
||||||
|
Bad:
|
||||||
|
|
||||||
|
- inject `Registry` into `BuilderPipelineService` because static state looks
|
||||||
|
like a service locator;
|
||||||
|
- create `frontends/synth` as a product module;
|
||||||
|
- add validator-core "so the next language has somewhere to put checks";
|
||||||
|
- keep `new PBSFrontendPhaseService()` in pipeline code and call that
|
||||||
|
simpler than going through the provider.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- The original agenda order ("before the other agendas") is historical.
|
||||||
|
Do not reopen DSC-0054..DSC-0064 to satisfy it.
|
||||||
|
- Static registry plus explicit `register`/`unregister` is visible. Hidden
|
||||||
|
`ServiceLoader` discovery is not the same thing.
|
||||||
|
- A second product frontend *is* a real consumer. Do not use this lesson to
|
||||||
|
refuse that frontend; use it to refuse infrastructure that frontend does
|
||||||
|
not yet need.
|
||||||
|
- Spec 23 already forbids plugin discovery. Do not duplicate it. Do not
|
||||||
|
treat silence in spec 23 as permission for RPC or validator-core.
|
||||||
|
- Simplicity does not mean PBS may leak into common modules. LSN-0066 still
|
||||||
|
owns that boundary.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Decision: `DEC-0051`
|
||||||
|
- Plan: `PLN-0130`
|
||||||
|
- Related lessons: `LSN-0055`, `LSN-0060`, `LSN-0063`, `LSN-0064`,
|
||||||
|
`LSN-0065`, `LSN-0066`
|
||||||
|
- `docs/specs/compiler/23. Compiler Pipeline Entry Points Specification.md`
|
||||||
|
(§2, §8.3)
|
||||||
|
- `prometeu-compiler/prometeu-frontend-registry/src/main/java/p/studio/compiler/FrontendRegistryService.java`
|
||||||
|
- `prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendProvider.java`
|
||||||
|
- `prometeu-app/src/main/java/p/studio/AppContainer.java`
|
||||||
+70
@@ -0,0 +1,70 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0074
|
||||||
|
ticket: pbs-lsp-remaining-editor-surface
|
||||||
|
title: PBS remaining editor surface is frontend-owned and transported by the LSP
|
||||||
|
created: 2026-09-22
|
||||||
|
tags: [studio, lsp, vscode, compiler-pbs, editor]
|
||||||
|
---
|
||||||
|
|
||||||
|
# PBS remaining editor surface is frontend-owned and transported by the LSP
|
||||||
|
|
||||||
|
## Original Problem
|
||||||
|
|
||||||
|
Nine open LSP agendas still described formatting, imports, semantic tokens, snapshots, completion, folding, diagnostics, document links, and call hierarchy as if none of that surface existed. By the time those agendas were still open, the server already advertised hover, completion, signature help, definition, references, outline, workspace symbols, rename, quick fix, and full semantic tokens. Each request still rebuilt analysis. References and rename had already shipped without a snapshot cache. There was no diagnostic whose meaning was "this name is not imported."
|
||||||
|
|
||||||
|
Treating the nine agendas as nine decisions would have reimplemented finished work and locked stale premises.
|
||||||
|
|
||||||
|
## Consolidated Decision
|
||||||
|
|
||||||
|
`DEC-0058` retired that split. One plan, `PLN-0137`, landed seven steps. The frontend produces the editorial result. The LSP transports it and does not invent a second policy. A missing capability is not advertised and returns an empty list, not a protocol error.
|
||||||
|
|
||||||
|
The wave explicitly does not add a project snapshot cache, type hierarchy, `completionItem/resolve`, snippets, a ranking score, range or on-type formatting, organize imports, a missing-import quick fix, `relatedInformation`, or a new semantic-token key.
|
||||||
|
|
||||||
|
1. Published editor diagnostic `source` is the bound frontend `languageId`. For PBS that is `pbs`. `code` stays the stable compiler code. The code is not copied into `source`.
|
||||||
|
2. A document link covers only the span of a `ModuleRef` whose module assembly already resolved to a regular file. Virtual stdlib and unresolved modules produce no link.
|
||||||
|
3. Folding comes from recovered spans of the listed declarations, their bodies, parameter lists, and `Doc` text blocks. A brace, parenthesis, or text block the tree does not cover still folds, including an unmatched opener through the end of the text. Selection grows outward from identifier, to argument or parameter list, to block or `Doc` text block, to declaration.
|
||||||
|
4. Formatting is full-document only. It reprints the token stream, indents by four spaces where brace or parenthesis nesting changes, leaves `Doc` text-block interiors untouched, and does not reorder declarations or move comments off their line.
|
||||||
|
5. Semantic tokens keep `PBSSemanticTokenProvider` as the baseline. Hover resolution may replace an identifier token only when an existing `PbsSemanticKind` matches the symbol. Failure, a broken file, or a symbol with no existing key keeps the baseline token.
|
||||||
|
6. Completion inside a `ModuleRef` lists project and stdlib modules the current resolver can already name. Every other offset keeps the existing member or general completion. Items stay eager and `resolveProvider` stays false.
|
||||||
|
7. Call hierarchy walks `CallExpr` nodes for functions and methods. It does not use the references index. A cursor that is not on a callable is empty. Type hierarchy is not advertised.
|
||||||
|
|
||||||
|
## Final Implementation
|
||||||
|
|
||||||
|
`CompilerLanguageServiceBridge` reads `LspProjectContext.languageId` into `BaselineDocumentIssue.source`. Document links read the physical module map that module assembly already built; stdlib files under `/virtual/stdlib` are not regular files, so they are not links. Folding, selection, and formatting reparse the open buffer with the existing lexer and parser. They do not require a successful project analysis. The semantic-token overlay runs only when editorial context is available and otherwise returns the provider tokens, including when project discovery fails. Module completion labels are the project modules from that same physical map plus the modules `ResourceStdlibEnvironmentResolver` can already resolve. Call hierarchy collects function, method, and constructor declarations from the recovered AST and matches `CallExpr` callees by name and call shape.
|
||||||
|
|
||||||
|
Spec 23 §8.3 states each of these rules. The nine earlier agendas, `AGD-0048` through `AGD-0056`, were abandoned and are not normative.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
A project import `@app:a` that resolves to `src/a/source.pbs` is one document link on that module-reference span. `@sdk:log` is not, because the stdlib file is virtual.
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
fn helper() -> int { return 1; }
|
||||||
|
fn main() -> int { return helper; }
|
||||||
|
```
|
||||||
|
|
||||||
|
The use of `helper` without a call is an identifier in the lexical pass. Hover resolves it as a function, so the overlay key is `pbs-function`. A local such as `value` has no existing key, so it stays `pbs-identifier`.
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
fn helper() -> int { return 1; }
|
||||||
|
fn main() -> int { return helper(); }
|
||||||
|
```
|
||||||
|
|
||||||
|
Prepare on `main` returns that function. Outgoing calls include `helper`. Incoming calls of `helper` include `main`. A cursor on a struct name returns no item.
|
||||||
|
|
||||||
|
## Common Pitfalls
|
||||||
|
|
||||||
|
- Do not copy the diagnostic code into `source`. The editor then shows the code twice and loses the language id.
|
||||||
|
- Do not build document links to `/virtual/stdlib`. Definition already refuses that destination.
|
||||||
|
- Do not treat document symbols as folding ranges. Outline and folding are different payloads.
|
||||||
|
- Do not pretty-print from the AST. Comments and `Doc` text-block interiors are not fully modeled as trivia on the tree.
|
||||||
|
- Do not add `pbs-local`, `pbs-parameter`, or `pbs-field` in the overlay. Those symbols stay on the baseline token until a later decision adds the key.
|
||||||
|
- Do not implement call hierarchy by inverting the references index. A reference is a use of a name, not a call.
|
||||||
|
- Do not start a snapshot cache because a later feature feels slow. This wave deliberately kept request-local analysis.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- `DEC-0058` and `PLN-0137`, removed by housekeeping after this lesson
|
||||||
|
- `docs/specs/compiler/23. Compiler Pipeline Entry Points Specification.md` §8.3
|
||||||
|
- Earlier surface: `LSN-0068`, `LSN-0069`, `LSN-0070`, `LSN-0071`, `LSN-0072`, `LSN-0073`
|
||||||
|
- Abandoned agendas: `AGD-0048` through `AGD-0056`
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0005
|
|
||||||
ticket: variable-tile-bank-palette-serialization
|
|
||||||
title: Variable Tile Bank Palette Serialization
|
|
||||||
status: open
|
|
||||||
created: 2026-03-26
|
|
||||||
resolved:
|
|
||||||
decision:
|
|
||||||
tags:
|
|
||||||
- packer
|
|
||||||
- legacy-import
|
|
||||||
- tile-bank
|
|
||||||
- palette-serialization
|
|
||||||
- versioning
|
|
||||||
---
|
|
||||||
|
|
||||||
## Pain
|
|
||||||
|
|
||||||
The current tile-bank contract serializes a fixed block of `64` palettes in v1 even when an asset authors far fewer palettes.
|
|
||||||
|
|
||||||
That keeps decoding simple, but it wastes cartridge space and leaves the system with a deliberate mismatch between authored and serialized palette counts.
|
|
||||||
|
|
||||||
## Context
|
|
||||||
|
|
||||||
Legacy source: `docs/packer/agendas/Variable Tile Bank Palette Serialization Agenda.md`
|
|
||||||
|
|
||||||
Domain owner: `docs/packer`
|
|
||||||
Cross-domain dependency:
|
|
||||||
|
|
||||||
- runtime
|
|
||||||
|
|
||||||
Current aligned v1 contract:
|
|
||||||
|
|
||||||
- pixels are serialized as packed `u4`;
|
|
||||||
- palettes are serialized as `RGB565 u16`;
|
|
||||||
- `palette_count = 64`;
|
|
||||||
- payload size includes a fixed `64 * 16 * 2` palette block.
|
|
||||||
|
|
||||||
The packer now exposes:
|
|
||||||
|
|
||||||
- `metadata.palette_count = 64`
|
|
||||||
- `metadata.palette_authored = <actual authored count>`
|
|
||||||
|
|
||||||
## Open Questions
|
|
||||||
|
|
||||||
- [ ] Should variable palette serialization arrive as a new payload version or as an incompatible change to the current one?
|
|
||||||
- [ ] If `palette_count` becomes variable, should runtime still materialize a 64-slot resident bank, or truly shrink in-memory representation too?
|
|
||||||
- [ ] Should sparse authored palette indices remain sparse in serialization, or be canonicalized into a dense runtime block?
|
|
||||||
- [ ] Which domain owns compatibility for existing cartridges: `packer`, `runtime`, or `shipper`?
|
|
||||||
|
|
||||||
## Options
|
|
||||||
|
|
||||||
### Option A - Keep fixed 64-palette serialization
|
|
||||||
- **Approach:** Preserve the current fixed v1 payload with zero-filled unused palette slots.
|
|
||||||
- **Pro:** No runtime change and current specs/tests remain stable.
|
|
||||||
- **Con:** Every glyph bank keeps paying the full palette cost.
|
|
||||||
- **Maintainability:** Medium.
|
|
||||||
|
|
||||||
### Option B - Move to variable palette serialization now
|
|
||||||
- **Approach:** Serialize only authored palettes and shrink payload size immediately.
|
|
||||||
- **Pro:** Better cartridge efficiency and tighter semantics for `palette_count`.
|
|
||||||
- **Con:** Reopens a just-stabilized cross-domain runtime contract and forces compatibility decisions now.
|
|
||||||
- **Maintainability:** Medium if done carefully, risky if done incidentally.
|
|
||||||
|
|
||||||
### Option C - Keep v1 fixed and design variable serialization for v2
|
|
||||||
- **Approach:** Preserve v1 stability now and open a later versioned follow-up for variable palette serialization.
|
|
||||||
- **Pro:** Keeps current work stable while preserving a clean path for future optimization.
|
|
||||||
- **Con:** Known waste remains in v1.
|
|
||||||
- **Maintainability:** Strong.
|
|
||||||
|
|
||||||
## Discussion
|
|
||||||
|
|
||||||
The retained agenda recommendation is already clear: the waste is real, but it is not a correctness bug, and reopening the runtime-facing contract immediately would mix optimization work into a freshly stabilized path.
|
|
||||||
|
|
||||||
That makes versioned follow-up a cleaner vehicle than incidental mutation of the current contract.
|
|
||||||
|
|
||||||
## Resolution
|
|
||||||
|
|
||||||
Recommended direction: adopt **Option C**.
|
|
||||||
|
|
||||||
Imported retained recommendation:
|
|
||||||
|
|
||||||
1. keep the current fixed 64-palette contract for v1;
|
|
||||||
2. if variable serialization is desired, design it explicitly as a versioned follow-up;
|
|
||||||
3. treat compatibility, runtime representation, and sparse-vs-dense palette identity as explicit next-wave questions rather than silent payload tweaks.
|
|
||||||
|
|
||||||
Next step suggestion: if the team wants to remove the fixed padding, open the corresponding runtime-side discussion and close the versioning/compatibility story before planning implementation.
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0039
|
|
||||||
ticket: pbs-symbol-documentation-and-hover-markdown
|
|
||||||
title: Modelo de documentacao de simbolos em PBS e consumo markdown no hover
|
|
||||||
status: open
|
|
||||||
created: 2026-05-08
|
|
||||||
tags: [compiler, compiler-pbs, studio, lsp, vscode, editor, hover, documentation, markdown]
|
|
||||||
---
|
|
||||||
|
|
||||||
## Pain
|
|
||||||
|
|
||||||
A wave atual de assistencia editorial quer `hover` util, mas ainda nao existe um modelo claro para documentacao authored dentro de PBS.
|
|
||||||
|
|
||||||
Sem esse modelo, o hover pode até mostrar:
|
|
||||||
|
|
||||||
- kind;
|
|
||||||
- assinatura;
|
|
||||||
- origem;
|
|
||||||
- tipo/shape.
|
|
||||||
|
|
||||||
Mas continua sem uma superficie limpa para explicar intencao de uso, contrato semantico, detalhes de parametros ou observacoes de API.
|
|
||||||
|
|
||||||
Hoje a ideia proposta eh algo como:
|
|
||||||
|
|
||||||
- `Document(qualquer markdown aqui dentro...)`
|
|
||||||
|
|
||||||
como anotacao consumida diretamente pelo hover.
|
|
||||||
|
|
||||||
Isso parece simples no uso, mas toca em decisoes de linguagem e contrato editorial que merecem discussao propria.
|
|
||||||
|
|
||||||
## Context
|
|
||||||
|
|
||||||
Domain owner: `compiler/pbs`
|
|
||||||
|
|
||||||
Subdomains touched:
|
|
||||||
|
|
||||||
- `compiler/general`
|
|
||||||
- `studio/lsp`
|
|
||||||
- `tools/vscode-extension`
|
|
||||||
|
|
||||||
Esta agenda eh deliberadamente separada de `AGD-0038`.
|
|
||||||
|
|
||||||
Razao:
|
|
||||||
|
|
||||||
- `AGD-0038` trata da wave 1 de `completion`, `hover` e `signature help`;
|
|
||||||
- esta nova agenda trata da autoria, armazenamento, propagacao e consumo de documentacao de simbolos.
|
|
||||||
|
|
||||||
O objetivo eh evitar que a primeira wave de assistencia editorial fique bloqueada por uma decisao de linguagem ainda nao fechada.
|
|
||||||
|
|
||||||
## Open Questions
|
|
||||||
|
|
||||||
- A autoria da documentacao deve acontecer por anotacao explicita como `Document(...)`, por comentario estruturado, ou por outro mecanismo?
|
|
||||||
- O payload authored deve aceitar markdown arbitrario como fonte canonica, ou deve haver alguma normalizacao/restricao?
|
|
||||||
- Quais simbolos podem carregar documentacao na wave inicial:
|
|
||||||
funcoes, methods, services, hosts, builtin types, structs, enums, fields, constructors?
|
|
||||||
- A documentacao deve viver no AST/semantics como superficie compiler-backed explicita?
|
|
||||||
- Como a documentacao authored em PBS se relaciona com documentacao de stdlib gerada ou importada de outras fontes?
|
|
||||||
- O hover deve consumir markdown pronto sem transformacao, ou deve haver um pipeline intermediario de sanitizacao/normalizacao?
|
|
||||||
- Como tratar multilinhas, escaping e ergonomia de escrita se a surface for `Document(...)`?
|
|
||||||
- A agenda deve definir apenas o modelo de autoria, ou tambem o transporte LSP e a composicao final do hover?
|
|
||||||
|
|
||||||
## Options
|
|
||||||
|
|
||||||
### Option A - Anotacao `Document(...)` com markdown como payload canonico
|
|
||||||
|
|
||||||
- **Approach:** introduzir uma anotacao explicita na linguagem PBS cujo conteudo ja eh markdown pronto para o hover.
|
|
||||||
- **Pro:** autoria direta, intencao clara, pipeline simples de consumo no LSP e no hover.
|
|
||||||
- **Con:** precisa desenhar sintaxe, escaping, multiline e regras de onde a anotacao eh permitida.
|
|
||||||
- **Maintainability:** forte se a surface de linguagem ficar limpa.
|
|
||||||
|
|
||||||
### Option B - Comentarios estruturados como fonte de documentacao
|
|
||||||
|
|
||||||
- **Approach:** usar comentarios especiais ou doc-comments, com parser especifico para gerar documentacao de simbolo.
|
|
||||||
- **Pro:** mais familiar para quem vem de outras linguagens e menos intrusivo no corpo semantico da linguagem.
|
|
||||||
- **Con:** exige novo contrato de binding entre comentarios e simbolos, e pode aumentar ambiguidade editorial.
|
|
||||||
- **Maintainability:** media.
|
|
||||||
|
|
||||||
### Option C - Nao definir autoria em PBS agora e suportar apenas docs de stdlib por metadata externa
|
|
||||||
|
|
||||||
- **Approach:** deixar a linguagem sem surface authored por enquanto e alimentar hover apenas com docs externas/geradas.
|
|
||||||
- **Pro:** menor custo imediato de linguagem.
|
|
||||||
- **Con:** resolve mal a autoria de codigo de usuario e deixa o modelo incompleto.
|
|
||||||
- **Maintainability:** fraca.
|
|
||||||
|
|
||||||
## Tradeoffs
|
|
||||||
|
|
||||||
Option C nao parece suficiente como direcao de produto se a intencao eh ter hover realmente util para APIs authored em PBS.
|
|
||||||
|
|
||||||
Option B eh plausivel, mas move o problema para um binding entre comentario e simbolo que tambem precisa ser projetado com cuidado. Isso costuma parecer mais barato do que realmente eh.
|
|
||||||
|
|
||||||
Option A tem um custo claro de sintaxe e modelo, mas pelo menos deixa explicito que documentacao eh metadado semantico e nao apenas texto solto ao redor do codigo.
|
|
||||||
|
|
||||||
Se a equipe realmente quer markdown authored pronto para consumo no hover, Option A parece a discussao mais direta e honesta.
|
|
||||||
|
|
||||||
## Recommendation
|
|
||||||
|
|
||||||
Discutir esta agenda com viés inicial para **Option A**, mas sem fechar ainda a sintaxe final.
|
|
||||||
|
|
||||||
A recomendacao preliminar eh separar o problema em duas perguntas:
|
|
||||||
|
|
||||||
1. qual eh a surface canonical de autoria da documentacao em PBS?
|
|
||||||
2. como essa documentacao vira um payload editorial resolvido para hover e futuros consumers?
|
|
||||||
|
|
||||||
Mesmo que `Document(...)` seja a direcao vencedora, a decisao deve deixar claro:
|
|
||||||
|
|
||||||
- onde ela pode ser usada;
|
|
||||||
- qual formato textual aceita;
|
|
||||||
- como ela eh preservada no compiler;
|
|
||||||
- como chega ao LSP;
|
|
||||||
- e como o hover deve compor isso com assinatura e metadados do simbolo.
|
|
||||||
|
|
||||||
## Discussion
|
|
||||||
|
|
||||||
Esta agenda nao deve ser reduzida a "mostrar markdown no hover".
|
|
||||||
|
|
||||||
O problema real eh definir ownership e boundary da documentacao:
|
|
||||||
|
|
||||||
- o author escreve onde?
|
|
||||||
- o compiler preserva como?
|
|
||||||
- o LSP transporta em qual shape?
|
|
||||||
- o hover monta o resultado com qual ordem e responsabilidade?
|
|
||||||
|
|
||||||
Tambem vale observar que a escolha aqui pode influenciar mais do que hover:
|
|
||||||
|
|
||||||
- completions futuras podem querer `detail` e `documentation`;
|
|
||||||
- signature help pode querer descricoes de parametros;
|
|
||||||
- docs de stdlib podem querer surface unificada com docs authored.
|
|
||||||
|
|
||||||
Por isso, mesmo sendo uma agenda separada, ela conversa diretamente com a futura qualidade do editor.
|
|
||||||
|
|
||||||
## Resolution
|
|
||||||
|
|
||||||
Ainda em aberto.
|
|
||||||
|
|
||||||
## Next Step
|
|
||||||
|
|
||||||
Se o enquadramento fizer sentido, o proximo passo eh discutir as open questions e fechar uma `decision` propria para o modelo de documentacao de simbolos em PBS.
|
|
||||||
@@ -1,273 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0041
|
|
||||||
ticket: studio-packer-rgba8888-asset-pipeline
|
|
||||||
title: Agenda - Studio and Packer RGBA8888 Asset Pipeline Alignment
|
|
||||||
status: accepted
|
|
||||||
created: 2026-05-23
|
|
||||||
resolved: 2026-05-23
|
|
||||||
decision: DEC-0037
|
|
||||||
tags:
|
|
||||||
- studio
|
|
||||||
- packer
|
|
||||||
- assets
|
|
||||||
- glyph-bank
|
|
||||||
- palette
|
|
||||||
- rgba8888
|
|
||||||
- runtime-alignment
|
|
||||||
---
|
|
||||||
|
|
||||||
## Pain
|
|
||||||
|
|
||||||
Domain owner: `studio`, with direct subdomain ownership in `packer` and
|
|
||||||
cross-domain dependency on `runtime`.
|
|
||||||
|
|
||||||
The runtime RGBA8888 migration changes the color contract underneath the Studio
|
|
||||||
asset pipeline. Runtime `DEC-0029` says RGBA8888 is the single canonical logical
|
|
||||||
color and physical framebuffer format, and that asset packages must encode
|
|
||||||
palettes as RGBA8888 without preserving RGB565 compatibility.
|
|
||||||
|
|
||||||
Studio still carries RGB565 in the packer-facing asset pipeline:
|
|
||||||
|
|
||||||
- `docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md`
|
|
||||||
defines `GLYPH/indexed_v1` palette payloads as `64 * 16 * 2` bytes of
|
|
||||||
little-endian `RGB565` values.
|
|
||||||
- `PackerPaletteV1` stores both `originalArgb8888` and `convertedRgb565`.
|
|
||||||
- `PackerGlyphBankWalker` drops partial alpha, treats alpha 0 and magenta as
|
|
||||||
transparent index `0`, stores only RGB identity for palette lookup, and
|
|
||||||
converts palette colors to RGB565.
|
|
||||||
- `PackerAssetDetailsService`, `PackerReadMessageMapper`, test fixtures, and
|
|
||||||
project `asset.json` files expose `convertedRgb565` as normal pipeline data.
|
|
||||||
|
|
||||||
The problem is not only changing one serializer. The Studio/packer side must
|
|
||||||
decide how authoring metadata, palette UI/data, emitted `assets.pa`, tests, and
|
|
||||||
existing project fixtures align with runtime RGBA channel order and meaningful
|
|
||||||
alpha.
|
|
||||||
|
|
||||||
## Context
|
|
||||||
|
|
||||||
Runtime discussion context:
|
|
||||||
|
|
||||||
- `../runtime/discussion/workflow/agendas/AGD-0037-rgba8888-framebuffer-and-pixel-format-direction.md`
|
|
||||||
was consulted as the originating discussion.
|
|
||||||
- `../runtime/discussion/workflow/decisions/DEC-0029-rgba8888-runtime-pixel-format-contract.md`
|
|
||||||
is accepted and normative for runtime.
|
|
||||||
- Runtime plans already split execution across specs, HAL/ABI, renderer,
|
|
||||||
asset palettes/tooling, host presentation, and validation.
|
|
||||||
|
|
||||||
Relevant runtime invariants for this Studio discussion:
|
|
||||||
|
|
||||||
- raw color values use RGBA channel order;
|
|
||||||
- asset package palettes must be RGBA8888;
|
|
||||||
- old RGB565 palette assets are not compatible runtime input;
|
|
||||||
- indexed tile/sprite payloads may remain indexed/paletized;
|
|
||||||
- transparency is represented by alpha in the resolved palette entry, not by
|
|
||||||
reserving palette index `0` as a special transparent index;
|
|
||||||
- RGB565 helpers may exist only as temporary migration utilities, not the
|
|
||||||
normal runtime path.
|
|
||||||
|
|
||||||
Relevant Studio/packer state:
|
|
||||||
|
|
||||||
- `assets.pa` is the authoritative runtime-facing artifact owned by the packer.
|
|
||||||
- `output.pipeline` is tooling-only by default, but current glyph palette data
|
|
||||||
lives there and is used by packer details/read flows.
|
|
||||||
- `GLYPH/indexed_v1` currently emits a fixed 256x256 packed `u4` pixel plane
|
|
||||||
plus a fixed 64-palette RGB565 block.
|
|
||||||
- `DSC-0005` is still open around variable tile-bank palette serialization.
|
|
||||||
That discussion optimizes fixed-vs-variable palette count. RGBA8888 changes
|
|
||||||
the color encoding and transparency semantics first, so it should supersede
|
|
||||||
or reframe any RGB565 assumptions before variable palette work continues.
|
|
||||||
- Studio scene publication currently carries `palette_id` in scene pack
|
|
||||||
requests. Scene payload shape is mostly unaffected by color format, but scene
|
|
||||||
previews, palette defaults, validation, and any editor-visible palette data
|
|
||||||
must remain consistent with the glyph-bank contract.
|
|
||||||
|
|
||||||
## Open Questions
|
|
||||||
|
|
||||||
- [x] Should Studio keep the runtime-facing format name `GLYPH/indexed_v1` and
|
|
||||||
make it an incompatible v1 contract update, or should packer emit a new
|
|
||||||
explicit format/version such as `GLYPH/indexed_rgba8888_v1`?
|
|
||||||
- Keep `GLYPH/indexed_v1`. The structural change is in palette encoding; the
|
|
||||||
remaining glyph payload model stays stable.
|
|
||||||
- [x] What is the canonical authoring-side palette field name: keep
|
|
||||||
`originalArgb8888`, rename to `rgba8888`, or store structured channel data?
|
|
||||||
- Use `rgba8888` unless the decision stage finds a concrete tooling reason to
|
|
||||||
choose a more explicit variant.
|
|
||||||
- [x] How should Java `BufferedImage` ARGB input be converted to runtime RGBA
|
|
||||||
raw values without confusing storage order, JSON numeric representation, or
|
|
||||||
signed `int` display in tooling?
|
|
||||||
- Convert ARGB input to RGBA output directly at the packer boundary.
|
|
||||||
- [x] Does palette index `0` remain an ordinary palette slot immediately, as
|
|
||||||
runtime `DEC-0029` requires, or does Studio need a temporary migration step to
|
|
||||||
rewrite existing transparent-index assets into alpha-bearing palette entries?
|
|
||||||
- Palette index `0` becomes an ordinary palette slot. Glyph palettes therefore
|
|
||||||
have 16 usable colors, not 15 plus a reserved transparent index.
|
|
||||||
- [x] Should magenta color-key support disappear from Studio authoring now, or
|
|
||||||
survive only as an explicit import/conversion helper outside the normal pack
|
|
||||||
path?
|
|
||||||
- Magenta color-key support should disappear completely.
|
|
||||||
- [x] Should partial alpha in PNG tiles become first-class palette data, or
|
|
||||||
should the packer still reject/diagnose partial alpha until renderer behavior
|
|
||||||
is fully proven?
|
|
||||||
- Partial alpha becomes valid palette data now. Existing validations and
|
|
||||||
warnings that flatten or reject partial alpha should be removed.
|
|
||||||
- [x] Which existing fixtures and sample projects should be regenerated versus
|
|
||||||
deleted because they encode RGB565-specific expectations?
|
|
||||||
- `main` and `fragments` will be regenerated manually later; they should not
|
|
||||||
block the Studio/packer decision.
|
|
||||||
- [x] How should this agenda relate to `DSC-0005`: close it as superseded,
|
|
||||||
revise it after RGBA8888, or keep it open as a later palette-count
|
|
||||||
optimization?
|
|
||||||
- `DSC-0005` remains a later step. RGBA8888 should not absorb variable
|
|
||||||
palette-count serialization.
|
|
||||||
|
|
||||||
## Options
|
|
||||||
|
|
||||||
### Option A - Minimal serializer swap inside current names
|
|
||||||
|
|
||||||
- **Approach:** Keep current public names and `GLYPH/indexed_v1`, replace the
|
|
||||||
palette block with fixed `64 * 16 * 4` RGBA8888 entries, remove
|
|
||||||
`convertedRgb565`, and update tests/specs in place.
|
|
||||||
- **Pro:** Smallest naming churn and likely the fastest path to unblock runtime
|
|
||||||
asset decode.
|
|
||||||
- **Con:** The `v1` label would silently change binary meaning, which is risky
|
|
||||||
for fixtures, docs, and any stale build output.
|
|
||||||
- **Maintainability:** Medium. Fast, but it relies on the repository accepting a
|
|
||||||
coordinated breaking change with no compatibility ambiguity.
|
|
||||||
|
|
||||||
### Option B - Explicit RGBA8888 glyph payload format
|
|
||||||
|
|
||||||
- **Approach:** Add an explicit runtime-facing glyph format/version for the
|
|
||||||
RGBA8888 palette payload, retire RGB565 output from the normal pack path, and
|
|
||||||
update asset declarations, specs, materialization, tests, fixtures, and sample
|
|
||||||
projects to the new format.
|
|
||||||
- **Pro:** Makes the breaking contract visible in file format names, tests, and
|
|
||||||
diagnostics while still obeying the runtime decision not to support RGB565 as
|
|
||||||
compatible input.
|
|
||||||
- **Con:** More code and fixture churn; requires clear migration handling for
|
|
||||||
stale project declarations and generated build artifacts.
|
|
||||||
- **Maintainability:** Strong. The format boundary becomes explicit and easier
|
|
||||||
to audit.
|
|
||||||
|
|
||||||
### Option C - Broaden the wave into full palette model redesign
|
|
||||||
|
|
||||||
- **Approach:** Use the RGBA8888 migration to redesign palette count, sparse vs
|
|
||||||
dense indices, material palettes, import/export, alpha authoring UI, and scene
|
|
||||||
palette defaults in one decision.
|
|
||||||
- **Pro:** Could produce a cleaner long-term asset model and resolve `DSC-0005`
|
|
||||||
at the same time.
|
|
||||||
- **Con:** Mixes a mandatory runtime alignment with optional model improvements,
|
|
||||||
increasing risk and delaying the renderer/asset migration.
|
|
||||||
- **Maintainability:** Weak for this wave. Better reserved for follow-up after
|
|
||||||
the RGBA8888 contract is stable.
|
|
||||||
|
|
||||||
## Discussion
|
|
||||||
|
|
||||||
The discussion converged toward an in-place `GLYPH/indexed_v1` structural
|
|
||||||
update rather than a new format name. This keeps the glyph-bank identity stable:
|
|
||||||
indexed pixels, fixed emitted sheet shape, scene `palette_id` references, and
|
|
||||||
the broad runtime glyph-bank model remain the same. The incompatible change is
|
|
||||||
the palette block and palette metadata moving from RGB565-derived values to raw
|
|
||||||
RGBA8888.
|
|
||||||
|
|
||||||
The authoring/read projection should expose `rgba8888` as the canonical palette
|
|
||||||
field. Java image inputs may still arrive as ARGB through `BufferedImage`, but
|
|
||||||
that is an input representation only. The packer boundary converts ARGB to
|
|
||||||
runtime RGBA and the rest of the pipeline should speak RGBA8888.
|
|
||||||
|
|
||||||
Palette index `0` is no longer special. It becomes a normal usable palette
|
|
||||||
entry, which gives glyph palettes 16 usable colors. Transparency comes from the
|
|
||||||
alpha byte in the RGBA8888 palette value. As a consequence, the old magenta
|
|
||||||
color-key behavior should be removed completely, not retained as a normal
|
|
||||||
authoring shortcut or hidden compatibility rule.
|
|
||||||
|
|
||||||
Partial alpha is valid data in this model. The packer should preserve it in the
|
|
||||||
palette instead of warning, flattening, or rejecting it. Existing validations
|
|
||||||
around partial alpha and the 15-color limit are therefore stale and should be
|
|
||||||
rewritten around the new 16-entry RGBA palette contract.
|
|
||||||
|
|
||||||
Existing sample projects and fixtures that still carry RGB565 assumptions are
|
|
||||||
not part of the discussion blocker. `main` and `fragments` will be regenerated
|
|
||||||
later. `DSC-0005` remains a separate future discussion for palette-count
|
|
||||||
serialization and should not be folded into this RGBA8888 wave.
|
|
||||||
|
|
||||||
## Tradeoffs
|
|
||||||
|
|
||||||
### Compatibility vs explicit break
|
|
||||||
|
|
||||||
Runtime `DEC-0029` already rejects RGB565 compatibility for this migration.
|
|
||||||
Studio therefore should not preserve RGB565 input as a normal path. The open
|
|
||||||
tradeoff is whether the packer should make the break visible through a new
|
|
||||||
format/version or simply mutate the existing v1 meaning.
|
|
||||||
|
|
||||||
### Authoring convenience vs runtime truth
|
|
||||||
|
|
||||||
Java image tooling naturally reads pixels as ARGB ints. Runtime wants raw RGBA
|
|
||||||
channel order. Studio can keep ARGB only as an import-side implementation detail,
|
|
||||||
but packer output, public metadata, and tests need one unambiguous RGBA8888
|
|
||||||
representation.
|
|
||||||
|
|
||||||
### Indexed art identity vs alpha semantics
|
|
||||||
|
|
||||||
The indexed/palette model can remain. What changes is that every palette entry,
|
|
||||||
including index `0`, should be a real RGBA color. Transparent pixels should be
|
|
||||||
encoded by alpha, not by a hardwired index rule or magenta color key.
|
|
||||||
|
|
||||||
### Scope control vs complete cleanup
|
|
||||||
|
|
||||||
It is tempting to combine RGBA8888 with variable palette serialization from
|
|
||||||
`DSC-0005`. That should be resisted unless the decision explicitly expands
|
|
||||||
scope. RGBA8888 changes bytes per palette entry and transparency semantics;
|
|
||||||
palette count optimization is a separate axis.
|
|
||||||
|
|
||||||
## Recommendation
|
|
||||||
|
|
||||||
Adopt a refined Option A.
|
|
||||||
|
|
||||||
The Studio/packer decision should keep `GLYPH/indexed_v1` as the runtime-facing
|
|
||||||
format name, but redefine its palette block and palette metadata around
|
|
||||||
RGBA8888. This is an intentional structural break in the palette contract, not
|
|
||||||
a new glyph-bank format.
|
|
||||||
|
|
||||||
The recommended shape for the decision is:
|
|
||||||
|
|
||||||
1. emit palette entries as raw RGBA8888 values in runtime RGBA channel order;
|
|
||||||
2. replace `convertedRgb565` with canonical `rgba8888` data in authoring and
|
|
||||||
read/detail projections;
|
|
||||||
3. treat Java/PNG ARGB as an input decoding detail and convert deliberately at
|
|
||||||
the packer boundary;
|
|
||||||
4. make palette index `0` ordinary, yielding 16 usable palette entries;
|
|
||||||
5. represent transparency and partial transparency only through RGBA alpha;
|
|
||||||
6. remove magenta color-key behavior completely;
|
|
||||||
7. remove partial-alpha flattening/rejection and preserve partial alpha as
|
|
||||||
valid palette data;
|
|
||||||
8. preserve fixed 64-palette serialization for this wave unless a decision
|
|
||||||
explicitly revises `DSC-0005`;
|
|
||||||
9. regenerate or rewrite RGB565 fixtures instead of supporting stale RGB565
|
|
||||||
assets at runtime.
|
|
||||||
|
|
||||||
## Next Step
|
|
||||||
|
|
||||||
The agenda is ready to move to decision if the refined recommendation is
|
|
||||||
accepted.
|
|
||||||
|
|
||||||
The next artifact should be a Studio/packer decision that references runtime
|
|
||||||
`DEC-0029`, leaves `DSC-0005` for a later palette-count step, and defines
|
|
||||||
propagation targets for:
|
|
||||||
|
|
||||||
- `docs/specs/packer`;
|
|
||||||
- `docs/specs/studio`;
|
|
||||||
- `prometeu-packer` models, walkers, serializers, services, fixtures, and
|
|
||||||
tests;
|
|
||||||
- sample project assets;
|
|
||||||
- any Studio asset workspace UI/read projections that expose palette data.
|
|
||||||
|
|
||||||
## Resolution
|
|
||||||
|
|
||||||
Accepted on 2026-05-23.
|
|
||||||
|
|
||||||
The discussion is closed in favor of decision `DEC-0037`. The accepted
|
|
||||||
direction keeps `GLYPH/indexed_v1`, moves its palette contract to RGBA8888,
|
|
||||||
uses `rgba8888` as the canonical palette field, makes palette index `0`
|
|
||||||
ordinary, removes magenta color-key behavior completely, accepts partial alpha
|
|
||||||
as valid palette data, and leaves `DSC-0005` for a later palette-count
|
|
||||||
serialization step.
|
|
||||||
@@ -1,228 +0,0 @@
|
|||||||
---
|
|
||||||
id: DEC-0037
|
|
||||||
ticket: studio-packer-rgba8888-asset-pipeline
|
|
||||||
title: Studio and Packer RGBA8888 Asset Pipeline Contract
|
|
||||||
status: accepted
|
|
||||||
created: 2026-05-23
|
|
||||||
accepted: 2026-05-23
|
|
||||||
ref_agenda: AGD-0041
|
|
||||||
plans:
|
|
||||||
- PLN-0081
|
|
||||||
- PLN-0082
|
|
||||||
- PLN-0083
|
|
||||||
- PLN-0084
|
|
||||||
- PLN-0085
|
|
||||||
- PLN-0086
|
|
||||||
tags:
|
|
||||||
- studio
|
|
||||||
- packer
|
|
||||||
- assets
|
|
||||||
- glyph-bank
|
|
||||||
- palette
|
|
||||||
- rgba8888
|
|
||||||
- runtime-alignment
|
|
||||||
---
|
|
||||||
|
|
||||||
## Status
|
|
||||||
|
|
||||||
Accepted. Drafted from accepted agenda `AGD-0041` and accepted on
|
|
||||||
2026-05-23.
|
|
||||||
|
|
||||||
## Context
|
|
||||||
|
|
||||||
Runtime `DEC-0029` makes RGBA8888 the canonical logical color representation
|
|
||||||
and physical framebuffer format for Prometeu. It also requires asset package
|
|
||||||
palettes to use RGBA8888, rejects RGB565 compatibility as normal runtime input,
|
|
||||||
and defines transparency through alpha rather than a reserved palette index.
|
|
||||||
|
|
||||||
Studio embeds the packer and owns the asset authoring and publication pipeline
|
|
||||||
that emits `assets.pa`. Before this decision, the Studio/packer glyph-bank path
|
|
||||||
still carried RGB565 assumptions:
|
|
||||||
|
|
||||||
- `GLYPH/indexed_v1` palette payloads were specified as fixed
|
|
||||||
`64 * 16 * 2` RGB565 `u16` values.
|
|
||||||
- `PackerPaletteV1` exposed `originalArgb8888` and `convertedRgb565`.
|
|
||||||
- `PackerGlyphBankWalker` flattened partial alpha, treated alpha zero and
|
|
||||||
magenta as transparent index `0`, limited authored colors to 15 usable
|
|
||||||
entries, and converted colors to RGB565.
|
|
||||||
- Studio/packer read projections, details APIs, fixtures, and sample assets
|
|
||||||
exposed `convertedRgb565` as ordinary pipeline data.
|
|
||||||
|
|
||||||
The runtime decision is already normative for the color contract. This decision
|
|
||||||
locks how Studio and packer align their glyph-bank asset pipeline with it.
|
|
||||||
|
|
||||||
## Decision
|
|
||||||
|
|
||||||
Studio and packer SHALL keep the runtime-facing glyph payload format name
|
|
||||||
`GLYPH/indexed_v1`.
|
|
||||||
|
|
||||||
The `GLYPH/indexed_v1` glyph-bank model SHALL remain indexed/paletized. Indexed
|
|
||||||
pixel payloads, fixed emitted sheet shape, scene `palette_id` references, and
|
|
||||||
the broad glyph-bank identity remain stable.
|
|
||||||
|
|
||||||
The structural change is the palette contract. `GLYPH/indexed_v1` palette data
|
|
||||||
MUST move from RGB565-derived values to RGBA8888 values in runtime RGBA channel
|
|
||||||
order.
|
|
||||||
|
|
||||||
Packer output, packer metadata, Studio read/detail projections, tests, and
|
|
||||||
fixtures MUST stop treating RGB565 as the normal palette representation.
|
|
||||||
`convertedRgb565` MUST be removed from the normal authored and projected
|
|
||||||
palette contract.
|
|
||||||
|
|
||||||
The canonical authored/projected palette field for this wave SHALL be
|
|
||||||
`rgba8888`.
|
|
||||||
|
|
||||||
Java `BufferedImage` and PNG inputs MAY be read as ARGB by host APIs, but ARGB
|
|
||||||
is only an input representation. The packer boundary MUST convert ARGB input to
|
|
||||||
runtime RGBA8888 output deliberately before emitting or projecting canonical
|
|
||||||
palette data.
|
|
||||||
|
|
||||||
Palette index `0` MUST be an ordinary palette index. Glyph palettes SHALL have
|
|
||||||
16 usable entries, not 15 usable entries plus a reserved transparent index.
|
|
||||||
|
|
||||||
Transparency and partial transparency MUST be represented only by the alpha
|
|
||||||
channel in the RGBA8888 palette value.
|
|
||||||
|
|
||||||
Magenta color-key behavior MUST be removed completely from the normal Studio
|
|
||||||
and packer asset pipeline. Magenta MUST NOT remain a hidden compatibility rule,
|
|
||||||
normal authoring shortcut, or runtime-facing transparency encoding.
|
|
||||||
|
|
||||||
Partial alpha in PNG/glyph inputs SHALL be valid palette data. Packer behavior
|
|
||||||
that warns about, flattens, rejects, or otherwise strips partial alpha MUST be
|
|
||||||
removed or rewritten around the RGBA8888 palette contract.
|
|
||||||
|
|
||||||
The fixed 64-palette serialization model remains in scope for this wave unless
|
|
||||||
another accepted decision explicitly revises it. `DSC-0005` remains a later
|
|
||||||
palette-count serialization discussion and MUST NOT be folded into this
|
|
||||||
RGBA8888 migration by implication.
|
|
||||||
|
|
||||||
Existing `main` and `fragments` sample project assets may be regenerated
|
|
||||||
manually later. Their regeneration is not a blocker for this decision and MUST
|
|
||||||
NOT justify preserving RGB565 compatibility in the packer.
|
|
||||||
|
|
||||||
## Rationale
|
|
||||||
|
|
||||||
Keeping `GLYPH/indexed_v1` avoids renaming a format whose core identity remains
|
|
||||||
the same: indexed glyph pixels resolved through palettes. The incompatible part
|
|
||||||
is specifically the palette encoding and transparency semantics.
|
|
||||||
|
|
||||||
Making RGBA8888 the normal packer-side representation aligns Studio with
|
|
||||||
runtime `DEC-0029` without introducing a parallel RGB565 compatibility path.
|
|
||||||
This keeps the asset pipeline direct: authoring input is normalized once at the
|
|
||||||
packer boundary, and emitted runtime artifacts carry the runtime color contract.
|
|
||||||
|
|
||||||
Treating index `0` as ordinary is required because transparency now belongs to
|
|
||||||
the alpha channel. This also gives each glyph palette the full 16 authored
|
|
||||||
entries available from the indexed payload.
|
|
||||||
|
|
||||||
Removing magenta color-key behavior avoids a second transparency mechanism that
|
|
||||||
would conflict with meaningful alpha. Allowing partial alpha preserves source
|
|
||||||
image information and supports the broader RGBA8888 renderer direction.
|
|
||||||
|
|
||||||
Keeping fixed 64-palette serialization separates mandatory color-format
|
|
||||||
migration from later payload-size optimization. Palette count and sparse/dense
|
|
||||||
serialization remain independent questions.
|
|
||||||
|
|
||||||
## Technical Specification
|
|
||||||
|
|
||||||
### Runtime-Facing Glyph Payload
|
|
||||||
|
|
||||||
- The format name remains `GLYPH/indexed_v1`.
|
|
||||||
- The indexed pixel plane remains packed `u4`.
|
|
||||||
- The emitted glyph-bank sheet shape remains unchanged for this wave.
|
|
||||||
- The palette block changes from 2-byte RGB565 entries to 4-byte RGBA8888
|
|
||||||
entries.
|
|
||||||
- The fixed palette block remains `64 * 16` entries for this wave.
|
|
||||||
- The byte-size formula for the palette block MUST be updated from
|
|
||||||
`64 * 16 * 2` to `64 * 16 * 4`.
|
|
||||||
- Size and decoded-size formulas for glyph-bank payloads MUST be updated
|
|
||||||
accordingly.
|
|
||||||
- Palette bytes MUST be interpreted as runtime RGBA channel order.
|
|
||||||
|
|
||||||
### Authored and Projected Palette Data
|
|
||||||
|
|
||||||
- Canonical palette data exposed by Studio/packer SHALL use `rgba8888`.
|
|
||||||
- `convertedRgb565` SHALL be removed from normal authored pipeline metadata,
|
|
||||||
details projections, read projections, fixtures, and tests.
|
|
||||||
- `originalArgb8888` SHALL NOT be the canonical field for runtime-facing or
|
|
||||||
packer-projected palette data in this wave.
|
|
||||||
- ARGB values read from Java image APIs MUST be converted to RGBA8888 before
|
|
||||||
entering canonical packer metadata or emitted payloads.
|
|
||||||
|
|
||||||
### Transparency and Alpha
|
|
||||||
|
|
||||||
- Palette index `0` is ordinary.
|
|
||||||
- A glyph palette has 16 usable entries.
|
|
||||||
- Alpha `0`, alpha between `1` and `254`, and alpha `255` are all valid
|
|
||||||
palette-entry states.
|
|
||||||
- Partial alpha MUST be preserved as data.
|
|
||||||
- Packer warnings or validations that describe partial alpha as flattened,
|
|
||||||
ignored, or unsupported MUST be removed.
|
|
||||||
- Color limit validation MUST be rewritten for 16 usable palette entries.
|
|
||||||
|
|
||||||
### Removed Behaviors
|
|
||||||
|
|
||||||
- RGB565 palette emission is not a normal packer output.
|
|
||||||
- RGB565 palette projection is not a normal Studio/packer read or details
|
|
||||||
contract.
|
|
||||||
- Magenta color-key transparency is not supported in the normal path.
|
|
||||||
- Palette index `0` is not reserved for transparency.
|
|
||||||
- Runtime asset compatibility with stale RGB565 palette payloads is not a
|
|
||||||
Studio/packer requirement for this wave.
|
|
||||||
|
|
||||||
## Propagation Targets
|
|
||||||
|
|
||||||
### Specs
|
|
||||||
|
|
||||||
- `docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md`
|
|
||||||
- `docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md`
|
|
||||||
- `docs/specs/studio/4. Assets Workspace Specification.md`, if Studio-facing
|
|
||||||
palette read/projection behavior is documented there.
|
|
||||||
|
|
||||||
### Code
|
|
||||||
|
|
||||||
- `prometeu-packer` palette model types.
|
|
||||||
- `PackerGlyphBankWalker`.
|
|
||||||
- `PackerAssetWalker` glyph-bank size and metadata calculations.
|
|
||||||
- `PackerAssetDetailsService`.
|
|
||||||
- `PackerReadMessageMapper`.
|
|
||||||
- Any packer serializer/materializer that emits `assets.pa` glyph payloads.
|
|
||||||
- Studio asset workspace read/detail surfaces that display or depend on
|
|
||||||
palette metadata.
|
|
||||||
|
|
||||||
### Tests and Fixtures
|
|
||||||
|
|
||||||
- Packer glyph-bank walker tests.
|
|
||||||
- Asset declaration parser tests that mention `convertedRgb565`.
|
|
||||||
- Runtime asset materializer tests.
|
|
||||||
- File-system workspace service tests.
|
|
||||||
- Fixture `asset.json` files that still declare RGB565-derived palette data.
|
|
||||||
- Test expectations for alpha, 16 usable colors, and removed magenta color-key
|
|
||||||
behavior.
|
|
||||||
|
|
||||||
`main` and `fragments` project assets are expected to be regenerated manually
|
|
||||||
later and are not blockers for this decision.
|
|
||||||
|
|
||||||
## Constraints
|
|
||||||
|
|
||||||
- This decision MUST NOT introduce an RGB565 compatibility mode.
|
|
||||||
- This decision MUST NOT rename the runtime-facing format away from
|
|
||||||
`GLYPH/indexed_v1`.
|
|
||||||
- This decision MUST NOT change scene `palette_id` semantics except as needed
|
|
||||||
to ensure referenced glyph palettes now resolve RGBA8888 entries.
|
|
||||||
- This decision MUST NOT decide variable palette-count serialization.
|
|
||||||
- This decision MUST NOT close or revise `DSC-0005`; that discussion remains a
|
|
||||||
later palette-count optimization track.
|
|
||||||
- Any implementation plan derived from this decision MUST preserve all
|
|
||||||
normative requirements above unless the user explicitly requests a decision
|
|
||||||
revision.
|
|
||||||
|
|
||||||
## References
|
|
||||||
|
|
||||||
- Agenda: `AGD-0041`
|
|
||||||
- Runtime decision: `../runtime/discussion/workflow/decisions/DEC-0029-rgba8888-runtime-pixel-format-contract.md`
|
|
||||||
- Related future discussion: `DSC-0005`
|
|
||||||
|
|
||||||
## Revision Log
|
|
||||||
|
|
||||||
- 2026-05-23: Initial accepted decision from `AGD-0041`.
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0081
|
|
||||||
ticket: studio-packer-rgba8888-asset-pipeline
|
|
||||||
title: RGBA8888 Packer and Studio Spec Propagation
|
|
||||||
status: done
|
|
||||||
created: 2026-05-23
|
|
||||||
completed: 2026-05-23
|
|
||||||
ref_decisions:
|
|
||||||
- DEC-0037
|
|
||||||
tags:
|
|
||||||
- specs
|
|
||||||
- packer
|
|
||||||
- studio
|
|
||||||
- rgba8888
|
|
||||||
---
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Propagate `DEC-0037` into the normative Studio and packer specifications before
|
|
||||||
code implementation starts.
|
|
||||||
|
|
||||||
## Background
|
|
||||||
|
|
||||||
`DEC-0037` keeps `GLYPH/indexed_v1` but changes its palette contract from
|
|
||||||
RGB565 to RGBA8888. Specs currently still describe RGB565 palette bytes,
|
|
||||||
`convertedRgb565`, and a 2048-byte palette block.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
### Included
|
|
||||||
|
|
||||||
- Update packer specs for `asset.json` palette metadata and `assets.pa`
|
|
||||||
glyph-bank payload layout.
|
|
||||||
- Update Studio asset workspace specs if they expose palette metadata or
|
|
||||||
details/read projection behavior.
|
|
||||||
- Preserve the fixed 64-palette model and explicitly leave `DSC-0005` for a
|
|
||||||
later palette-count optimization.
|
|
||||||
|
|
||||||
### Excluded
|
|
||||||
|
|
||||||
- Code changes.
|
|
||||||
- Test changes.
|
|
||||||
- Variable palette-count serialization.
|
|
||||||
- Runtime spec changes, except references to runtime `DEC-0029`.
|
|
||||||
|
|
||||||
## Execution Steps
|
|
||||||
|
|
||||||
### Step 1 - Update asset declaration palette fields
|
|
||||||
|
|
||||||
**What:** Replace `originalArgb8888`/`convertedRgb565` examples and rules with
|
|
||||||
canonical `rgba8888`.
|
|
||||||
|
|
||||||
**How:** Edit the palette portions of the asset declaration spec so
|
|
||||||
`output.pipeline.palettes[*].palette.rgba8888` is the canonical field. State
|
|
||||||
that ARGB may be an input API detail but is not canonical authored/projected
|
|
||||||
palette data.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md`
|
|
||||||
|
|
||||||
### Step 2 - Update glyph-bank payload layout
|
|
||||||
|
|
||||||
**What:** Change `GLYPH/indexed_v1` palette layout from RGB565 to RGBA8888.
|
|
||||||
|
|
||||||
**How:** Keep the format name. Change the palette block from
|
|
||||||
`64 * 16 * 2 = 2048` bytes to `64 * 16 * 4 = 4096` bytes. Update size and
|
|
||||||
decoded-size formulas. State that palette entries use runtime RGBA channel
|
|
||||||
order.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md`
|
|
||||||
|
|
||||||
### Step 3 - Document alpha and index semantics
|
|
||||||
|
|
||||||
**What:** Document that palette index `0` is ordinary and all 16 palette entries
|
|
||||||
are usable.
|
|
||||||
|
|
||||||
**How:** Add normative rules that transparency and partial transparency are
|
|
||||||
encoded only by RGBA alpha, magenta color-key is removed, and partial alpha is
|
|
||||||
valid palette data.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md`
|
|
||||||
- `docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md`
|
|
||||||
|
|
||||||
### Step 4 - Update Studio-facing projection rules
|
|
||||||
|
|
||||||
**What:** Ensure Studio-facing docs use `rgba8888` where palette metadata is
|
|
||||||
visible.
|
|
||||||
|
|
||||||
**How:** Update asset workspace language only where it describes palette read,
|
|
||||||
details, scene preview, or palette default behavior. Keep scene `palette_id`
|
|
||||||
semantics unchanged.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `docs/specs/studio/4. Assets Workspace Specification.md`
|
|
||||||
|
|
||||||
## Test Requirements
|
|
||||||
|
|
||||||
### Unit Tests
|
|
||||||
|
|
||||||
- Not applicable for this spec-only plan.
|
|
||||||
|
|
||||||
### Integration Tests
|
|
||||||
|
|
||||||
- Not applicable for this spec-only plan.
|
|
||||||
|
|
||||||
### Manual Verification
|
|
||||||
|
|
||||||
- Search specs for stale `RGB565`, `convertedRgb565`, 2048-byte palette block,
|
|
||||||
reserved index `0`, and magenta color-key language.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- [x] Packer specs define `rgba8888` as the canonical palette field.
|
|
||||||
- [x] `GLYPH/indexed_v1` remains named exactly that.
|
|
||||||
- [x] Palette block formulas use `64 * 16 * 4 = 4096`.
|
|
||||||
- [x] Specs state palette index `0` is ordinary and all 16 entries are usable.
|
|
||||||
- [x] Specs state partial alpha is valid and magenta color-key is removed.
|
|
||||||
- [x] Specs leave `DSC-0005` variable palette-count work out of scope.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Depends on accepted `DEC-0037`.
|
|
||||||
- Should complete before code plans are implemented.
|
|
||||||
|
|
||||||
## Risks
|
|
||||||
|
|
||||||
- Leaving stale RGB565 examples in specs will make implementation review
|
|
||||||
ambiguous.
|
|
||||||
- Over-editing scene specs could accidentally imply a scene payload change that
|
|
||||||
`DEC-0037` does not authorize.
|
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0082
|
|
||||||
ticket: studio-packer-rgba8888-asset-pipeline
|
|
||||||
title: RGBA8888 Palette Model and ARGB Conversion
|
|
||||||
status: done
|
|
||||||
created: 2026-05-23
|
|
||||||
completed: 2026-05-23
|
|
||||||
ref_decisions:
|
|
||||||
- DEC-0037
|
|
||||||
tags:
|
|
||||||
- packer
|
|
||||||
- palette
|
|
||||||
- rgba8888
|
|
||||||
- conversion
|
|
||||||
---
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Replace the packer palette model with canonical RGBA8888 data and introduce a
|
|
||||||
single deliberate ARGB-to-RGBA conversion boundary for image inputs.
|
|
||||||
|
|
||||||
## Background
|
|
||||||
|
|
||||||
`PackerPaletteV1` currently stores `originalArgb8888` and `convertedRgb565`.
|
|
||||||
`PackerGlyphBankWalker` reads Java ARGB pixels, drops alpha semantics, reserves
|
|
||||||
index `0`, applies magenta color-key, and converts colors to RGB565.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
### Included
|
|
||||||
|
|
||||||
- Replace `PackerPaletteV1` fields with canonical `rgba8888`.
|
|
||||||
- Add or localize ARGB-to-RGBA conversion helpers.
|
|
||||||
- Preserve partial alpha.
|
|
||||||
- Remove RGB565 conversion from the normal palette model.
|
|
||||||
- Expand glyph palette extraction from 15 to 16 usable colors.
|
|
||||||
|
|
||||||
### Excluded
|
|
||||||
|
|
||||||
- Binary `assets.pa` emission changes.
|
|
||||||
- Read/detail API projection changes outside direct model compile fixes.
|
|
||||||
- Spec edits.
|
|
||||||
- Fixture regeneration for `main` and `fragments`.
|
|
||||||
|
|
||||||
## Execution Steps
|
|
||||||
|
|
||||||
### Step 1 - Replace the palette record
|
|
||||||
|
|
||||||
**What:** Change the packer palette model to carry canonical RGBA8888 values.
|
|
||||||
|
|
||||||
**How:** Replace `int[] originalArgb8888, short[] convertedRgb565` with
|
|
||||||
`int[] rgba8888`. Keep the record name only if it remains semantically useful;
|
|
||||||
otherwise rename only if all callers are updated in the same change.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/models/PackerPaletteV1.java`
|
|
||||||
|
|
||||||
### Step 2 - Convert ARGB image pixels to RGBA
|
|
||||||
|
|
||||||
**What:** Introduce one conversion path from Java `BufferedImage` ARGB to raw
|
|
||||||
runtime RGBA.
|
|
||||||
|
|
||||||
**How:** Convert `0xAARRGGBB` to `0xRRGGBBAA` when building palette entries.
|
|
||||||
Do not store ARGB in canonical packer metadata.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerGlyphBankWalker.java`
|
|
||||||
|
|
||||||
### Step 3 - Remove magenta color-key and reserved index behavior
|
|
||||||
|
|
||||||
**What:** Stop treating alpha zero or magenta as special palette-index behavior.
|
|
||||||
|
|
||||||
**How:** Remove `COLOR_KEY_RGB`. Build palette identity from full RGBA8888
|
|
||||||
values, including alpha. Assign indices from `0` through `15`.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerGlyphBankWalker.java`
|
|
||||||
|
|
||||||
### Step 4 - Preserve partial alpha
|
|
||||||
|
|
||||||
**What:** Remove partial-alpha warnings and flattening.
|
|
||||||
|
|
||||||
**How:** Delete the `partialAlphaFound` warning path. Ensure pixels with alpha
|
|
||||||
from `0` through `255` participate in palette extraction by full RGBA value.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerGlyphBankWalker.java`
|
|
||||||
|
|
||||||
### Step 5 - Update color-limit validation
|
|
||||||
|
|
||||||
**What:** Change validation from 15 usable colors to 16 usable colors.
|
|
||||||
|
|
||||||
**How:** Replace `MAX_COLORS_PER_PALETTE = 15` with a 16-entry limit and update
|
|
||||||
diagnostic wording to remove `indices 1..15`.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerGlyphBankWalker.java`
|
|
||||||
|
|
||||||
## Test Requirements
|
|
||||||
|
|
||||||
### Unit Tests
|
|
||||||
|
|
||||||
- Update `PackerGlyphBankWalkerTest` to assert:
|
|
||||||
- 16 unique RGBA colors are valid.
|
|
||||||
- a 17th unique RGBA color is blocking.
|
|
||||||
- alpha `0`, partial alpha, and alpha `255` are preserved.
|
|
||||||
- magenta is treated as an ordinary color.
|
|
||||||
- palette index `0` can hold an ordinary color.
|
|
||||||
|
|
||||||
### Integration Tests
|
|
||||||
|
|
||||||
- None for this plan; binary emission is covered by a later plan.
|
|
||||||
|
|
||||||
### Manual Verification
|
|
||||||
|
|
||||||
- Search packer model and glyph walker sources for `convertedRgb565`,
|
|
||||||
`originalArgb8888`, `COLOR_KEY_RGB`, `convertToRgb565`, and partial-alpha
|
|
||||||
warning text.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- [x] `PackerPaletteV1` exposes `rgba8888` and no RGB565 field.
|
|
||||||
- [x] `PackerGlyphBankWalker` stores canonical RGBA values.
|
|
||||||
- [x] Magenta is not special.
|
|
||||||
- [x] Alpha zero and partial alpha are valid palette data.
|
|
||||||
- [x] All 16 palette indices are usable.
|
|
||||||
- [x] Unit tests cover conversion and palette indexing semantics.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Depends on `PLN-0081` for spec wording.
|
|
||||||
- Must complete before payload emission and projection plans.
|
|
||||||
|
|
||||||
## Risks
|
|
||||||
|
|
||||||
- Confusing Java ARGB input with runtime RGBA output will create hard-to-debug
|
|
||||||
byte-order failures.
|
|
||||||
- Cache reuse may keep stale palette metadata if reusable metadata checks are
|
|
||||||
not updated with the model change.
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0083
|
|
||||||
ticket: studio-packer-rgba8888-asset-pipeline
|
|
||||||
title: RGBA8888 Glyph Payload Emission and Size Accounting
|
|
||||||
status: done
|
|
||||||
created: 2026-05-23
|
|
||||||
completed: 2026-05-23
|
|
||||||
ref_decisions:
|
|
||||||
- DEC-0037
|
|
||||||
tags:
|
|
||||||
- packer
|
|
||||||
- assets-pa
|
|
||||||
- glyph-bank
|
|
||||||
- rgba8888
|
|
||||||
---
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Change packer glyph-bank runtime payload emission from RGB565 palette bytes to
|
|
||||||
RGBA8888 palette bytes while keeping `GLYPH/indexed_v1` and the fixed
|
|
||||||
64-palette model.
|
|
||||||
|
|
||||||
## Background
|
|
||||||
|
|
||||||
`DEC-0037` requires `GLYPH/indexed_v1` to retain its format name and indexed
|
|
||||||
model but emit RGBA8888 palette entries. Current payload emission in
|
|
||||||
`FileSystemPackerWorkspaceService` writes RGB565 bytes, reserves index `0`, and
|
|
||||||
uses color-key bytes.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
### Included
|
|
||||||
|
|
||||||
- Update glyph-bank payload palette byte emission.
|
|
||||||
- Update measured payload size and decoded-size accounting.
|
|
||||||
- Remove RGB565 palette constants and palette color-key bytes from emission.
|
|
||||||
- Keep scene `palette_id` payload semantics unchanged.
|
|
||||||
|
|
||||||
### Excluded
|
|
||||||
|
|
||||||
- Palette model extraction changes covered by `PLN-0082`.
|
|
||||||
- Read/detail projection changes covered by `PLN-0084`.
|
|
||||||
- Variable palette count.
|
|
||||||
|
|
||||||
## Execution Steps
|
|
||||||
|
|
||||||
### Step 1 - Update glyph payload constants and formulas
|
|
||||||
|
|
||||||
**What:** Change palette entry width from 2 bytes to 4 bytes.
|
|
||||||
|
|
||||||
**How:** Introduce clear constants for palette count, colors per palette, and
|
|
||||||
RGBA bytes per color. Use `64 * 16 * 4` for palette block size.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java`
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerAssetWalker.java`
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerRuntimeAssetMaterializer.java`
|
|
||||||
|
|
||||||
### Step 2 - Emit RGBA8888 palette bytes
|
|
||||||
|
|
||||||
**What:** Write each palette color as runtime RGBA channel bytes.
|
|
||||||
|
|
||||||
**How:** Replace RGB565 little-endian writes with four byte writes in `R`, `G`,
|
|
||||||
`B`, `A` order derived from the canonical `rgba8888` integer value.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java`
|
|
||||||
|
|
||||||
### Step 3 - Remove reserved color-key emission
|
|
||||||
|
|
||||||
**What:** Stop writing a synthetic color-key value at palette index `0`.
|
|
||||||
|
|
||||||
**How:** Remove `GLYPH_BANK_COLOR_KEY_RGB565` and any emission path that fills
|
|
||||||
index `0` with magenta. Emit declared RGBA values for index `0` like every
|
|
||||||
other index.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java`
|
|
||||||
|
|
||||||
### Step 4 - Update declared palette lookup
|
|
||||||
|
|
||||||
**What:** Read `rgba8888` from declared pipeline metadata.
|
|
||||||
|
|
||||||
**How:** Replace `originalArgb8888`/`convertedRgb565` lookup paths with
|
|
||||||
`rgba8888`. Ensure empty or malformed `rgba8888` is structural failure where
|
|
||||||
emission requires a palette.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java`
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerAssetWalker.java`
|
|
||||||
|
|
||||||
### Step 5 - Keep scene payload stable
|
|
||||||
|
|
||||||
**What:** Preserve scene `palette_id` layout.
|
|
||||||
|
|
||||||
**How:** Do not change `writeSceneBankPayload` except compile fixes caused by
|
|
||||||
shared helper changes. Scene tile records continue carrying `palette_id` as an
|
|
||||||
index into the referenced glyph palette.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java`
|
|
||||||
|
|
||||||
## Test Requirements
|
|
||||||
|
|
||||||
### Unit Tests
|
|
||||||
|
|
||||||
- Add or update tests asserting glyph payload size includes a 4096-byte palette
|
|
||||||
block.
|
|
||||||
- Assert emitted palette bytes for a known RGBA value, including alpha.
|
|
||||||
- Assert index `0` emits declared RGBA data, not magenta.
|
|
||||||
|
|
||||||
### Integration Tests
|
|
||||||
|
|
||||||
- Update workspace build tests that read `build/assets.pa` and assert glyph-bank
|
|
||||||
offsets/sizes.
|
|
||||||
|
|
||||||
### Manual Verification
|
|
||||||
|
|
||||||
- Search production packer code for `GLYPH_BANK_COLOR_KEY_RGB565`,
|
|
||||||
`convertedRgb565`, RGB565 palette byte writes, and hard-coded `2048`.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- [x] Glyph payloads keep `GLYPH/indexed_v1`.
|
|
||||||
- [x] Glyph palette blocks are 4096 bytes.
|
|
||||||
- [x] Palette entries are emitted as RGBA bytes in runtime channel order.
|
|
||||||
- [x] No synthetic magenta/color-key value is emitted.
|
|
||||||
- [x] Size and decoded-size metadata match the new payload length.
|
|
||||||
- [x] Scene `palette_id` payload shape is unchanged.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Depends on `PLN-0082`.
|
|
||||||
- Should run before tests/fixture conformance in `PLN-0085`.
|
|
||||||
|
|
||||||
## Risks
|
|
||||||
|
|
||||||
- Updating size formulas without updating emitted bytes, or vice versa, will
|
|
||||||
corrupt payload slicing in `assets.pa`.
|
|
||||||
- Accidental scene payload edits could widen the change beyond `DEC-0037`.
|
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0084
|
|
||||||
ticket: studio-packer-rgba8888-asset-pipeline
|
|
||||||
title: RGBA8888 Packer Projections and Workspace APIs
|
|
||||||
status: done
|
|
||||||
created: 2026-05-23
|
|
||||||
completed: 2026-05-23
|
|
||||||
ref_decisions:
|
|
||||||
- DEC-0037
|
|
||||||
tags:
|
|
||||||
- packer
|
|
||||||
- studio
|
|
||||||
- api
|
|
||||||
- rgba8888
|
|
||||||
---
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Update packer and Studio-facing read/detail/write projections so palette data
|
|
||||||
is exposed and accepted as `rgba8888`, with no normal `convertedRgb565` or
|
|
||||||
canonical `originalArgb8888` surface.
|
|
||||||
|
|
||||||
## Background
|
|
||||||
|
|
||||||
`DEC-0037` requires packer metadata, Studio read/detail projections, tests, and
|
|
||||||
fixtures to stop treating RGB565 as normal palette data. Several services still
|
|
||||||
parse or project `originalArgb8888` and `convertedRgb565`.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
### Included
|
|
||||||
|
|
||||||
- Update parser and declaration normalization for palette metadata.
|
|
||||||
- Update read/detail mappers.
|
|
||||||
- Update palette-overhauling and bank-composition support to emit `rgba8888`.
|
|
||||||
- Preserve existing DTO shapes except for palette payload field names.
|
|
||||||
|
|
||||||
### Excluded
|
|
||||||
|
|
||||||
- Binary payload byte emission.
|
|
||||||
- Renderer/runtime changes.
|
|
||||||
- Manual regeneration of `main` and `fragments`.
|
|
||||||
|
|
||||||
## Execution Steps
|
|
||||||
|
|
||||||
### Step 1 - Update asset declaration parsing
|
|
||||||
|
|
||||||
**What:** Parse canonical `rgba8888` arrays from `asset.json`.
|
|
||||||
|
|
||||||
**How:** Replace palette validation that requires `originalArgb8888` and
|
|
||||||
`convertedRgb565` with validation for `rgba8888`. Keep numeric validation.
|
|
||||||
Reject malformed or missing `rgba8888` where a palette payload is required.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/PackerAssetDeclarationParser.java`
|
|
||||||
|
|
||||||
### Step 2 - Update details projection
|
|
||||||
|
|
||||||
**What:** Return `rgba8888` from asset details.
|
|
||||||
|
|
||||||
**How:** Change `palettePayloadFromNode` to project `{ index, rgba8888 }`.
|
|
||||||
Remove `convertedRgb565` and canonical `originalArgb8888` from details output.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/PackerAssetDetailsService.java`
|
|
||||||
|
|
||||||
### Step 3 - Update read message mapping
|
|
||||||
|
|
||||||
**What:** Map `PackerPaletteV1` and cached palette metadata to `rgba8888`.
|
|
||||||
|
|
||||||
**How:** Replace `originalArgb8888` and `convertedRgb565` mapping with a single
|
|
||||||
`rgba8888` array.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/PackerReadMessageMapper.java`
|
|
||||||
|
|
||||||
### Step 4 - Update workspace write operations
|
|
||||||
|
|
||||||
**What:** Ensure packer write APIs that apply palette changes persist `rgba8888`.
|
|
||||||
|
|
||||||
**How:** Replace palette-overhauling and related write-lane logic that requires
|
|
||||||
both `originalArgb8888` and `convertedRgb565` with a `rgba8888` contract.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java`
|
|
||||||
|
|
||||||
### Step 5 - Update cache reuse and walk projection checks
|
|
||||||
|
|
||||||
**What:** Make cache reuse validate new palette metadata.
|
|
||||||
|
|
||||||
**How:** Replace reusable metadata checks for `originalArgb8888` with
|
|
||||||
`rgba8888`. Stale cached RGB565-derived metadata must not be considered
|
|
||||||
reusable.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerGlyphBankWalker.java`
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerAssetWalker.java`
|
|
||||||
|
|
||||||
## Test Requirements
|
|
||||||
|
|
||||||
### Unit Tests
|
|
||||||
|
|
||||||
- Update parser tests to accept `rgba8888` and reject missing/malformed
|
|
||||||
`rgba8888`.
|
|
||||||
- Update details service tests to assert `rgba8888`.
|
|
||||||
- Update read mapper coverage for `PackerPaletteV1`.
|
|
||||||
- Update write operation tests for palette overhauling.
|
|
||||||
|
|
||||||
### Integration Tests
|
|
||||||
|
|
||||||
- Exercise a workspace read/build flow from `asset.json` using `rgba8888`.
|
|
||||||
|
|
||||||
### Manual Verification
|
|
||||||
|
|
||||||
- Search `prometeu-packer` for `originalArgb8888` and `convertedRgb565` after
|
|
||||||
this plan. Remaining matches must be migration-only or removed in later
|
|
||||||
fixture plan.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- [x] `asset.json` palette metadata uses `rgba8888`.
|
|
||||||
- [x] Details/read projections expose `rgba8888`.
|
|
||||||
- [x] Workspace write operations persist `rgba8888`.
|
|
||||||
- [x] Stale RGB565-derived cache metadata is not reused as canonical.
|
|
||||||
- [x] No normal API requires `convertedRgb565`.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Depends on `PLN-0082`.
|
|
||||||
- Can run partly in parallel with `PLN-0083` after the palette model is stable.
|
|
||||||
|
|
||||||
## Risks
|
|
||||||
|
|
||||||
- DTO consumers may assume old map keys. Tests must cover the Studio-facing
|
|
||||||
projection boundary.
|
|
||||||
- Cache reuse can hide stale behavior if not invalidated by metadata shape.
|
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0085
|
|
||||||
ticket: studio-packer-rgba8888-asset-pipeline
|
|
||||||
title: RGBA8888 Tests, Fixtures, and Conformance Updates
|
|
||||||
status: done
|
|
||||||
created: 2026-05-23
|
|
||||||
completed: 2026-05-23
|
|
||||||
ref_decisions:
|
|
||||||
- DEC-0037
|
|
||||||
tags:
|
|
||||||
- tests
|
|
||||||
- fixtures
|
|
||||||
- conformance
|
|
||||||
- rgba8888
|
|
||||||
---
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Update packer tests and fixtures so RGBA8888 is the asserted source of truth and
|
|
||||||
RGB565-specific expectations are removed.
|
|
||||||
|
|
||||||
## Background
|
|
||||||
|
|
||||||
`DEC-0037` requires tests and fixtures to stop proving RGB565 behavior. The code
|
|
||||||
base has parser, walker, details, materializer, and workspace service tests that
|
|
||||||
mention `convertedRgb565`, `originalArgb8888`, 15-color limits, magenta
|
|
||||||
color-key behavior, and RGB565 payload sizes.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
### Included
|
|
||||||
|
|
||||||
- Update packer unit tests and integration-style workspace tests.
|
|
||||||
- Update fixture `asset.json` files under packer test resources.
|
|
||||||
- Add conformance-oriented assertions for RGBA channel order, alpha, index `0`,
|
|
||||||
16 usable colors, and removed color-key behavior.
|
|
||||||
|
|
||||||
### Excluded
|
|
||||||
|
|
||||||
- Manual regeneration of `test-projects/main` and `fragments`.
|
|
||||||
- Production code changes except minor compile-fix test helpers.
|
|
||||||
- Runtime repository tests.
|
|
||||||
|
|
||||||
## Execution Steps
|
|
||||||
|
|
||||||
### Step 1 - Update parser and details tests
|
|
||||||
|
|
||||||
**What:** Replace palette payload fixtures with `rgba8888`.
|
|
||||||
|
|
||||||
**How:** Rewrite test JSON snippets and assertions that mention
|
|
||||||
`originalArgb8888` or `convertedRgb565`.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/services/PackerAssetDeclarationParserTest.java`
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/services/PackerAssetDetailsServiceTest.java`
|
|
||||||
|
|
||||||
### Step 2 - Update glyph walker tests
|
|
||||||
|
|
||||||
**What:** Assert new palette extraction semantics.
|
|
||||||
|
|
||||||
**How:** Add image fixtures in tests that cover:
|
|
||||||
16 colors, 17-color failure, alpha 0, partial alpha, magenta as ordinary color,
|
|
||||||
and index `0` as ordinary.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/repositories/PackerGlyphBankWalkerTest.java`
|
|
||||||
|
|
||||||
### Step 3 - Update materializer and workspace service tests
|
|
||||||
|
|
||||||
**What:** Assert RGBA8888 runtime payload and metadata behavior.
|
|
||||||
|
|
||||||
**How:** Update tests that read `assets.pa`, measured bank size, payload offsets,
|
|
||||||
and palette byte expectations. Replace RGB565 byte checks with RGBA byte checks.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/repositories/PackerRuntimeAssetMaterializerTest.java`
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/services/FileSystemPackerWorkspaceServiceTest.java`
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/services/PackerRuntimePatchServiceTest.java`
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/test/java/p/packer/services/PackerRuntimeRegistryTest.java`
|
|
||||||
|
|
||||||
### Step 4 - Update packer fixture assets
|
|
||||||
|
|
||||||
**What:** Replace fixture `asset.json` palette fields with `rgba8888`.
|
|
||||||
|
|
||||||
**How:** Edit packer test fixtures under `src/test/resources/fixtures` so
|
|
||||||
canonical palette declarations do not contain `convertedRgb565`.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `prometeu-packer/prometeu-packer-v1/src/test/resources/fixtures/**/asset.json`
|
|
||||||
|
|
||||||
### Step 5 - Add stale-contract guards
|
|
||||||
|
|
||||||
**What:** Add tests or quality checks that catch old RGB565 palette contract
|
|
||||||
residue.
|
|
||||||
|
|
||||||
**How:** Add assertions in existing tests or a focused repository quality test
|
|
||||||
that normal packer specs/tests/fixtures do not contain `convertedRgb565` or
|
|
||||||
RGB565 glyph palette payload expectations.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- Existing packer test suites under `prometeu-packer/prometeu-packer-v1/src/test/java`
|
|
||||||
|
|
||||||
## Test Requirements
|
|
||||||
|
|
||||||
### Unit Tests
|
|
||||||
|
|
||||||
- Parser, details, mapper, glyph walker, and workspace service unit tests must
|
|
||||||
all pass.
|
|
||||||
|
|
||||||
### Integration Tests
|
|
||||||
|
|
||||||
- Run the relevant Gradle test task for `prometeu-packer-v1`.
|
|
||||||
|
|
||||||
### Manual Verification
|
|
||||||
|
|
||||||
- Search for `convertedRgb565`, `originalArgb8888`, `RGB565`, `rgb565`, `2048`,
|
|
||||||
and magenta color-key references in packer tests and fixtures.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- [x] Tests use `rgba8888` as canonical palette data.
|
|
||||||
- [x] Tests assert RGBA channel order and alpha preservation.
|
|
||||||
- [x] Tests assert 16 usable palette entries.
|
|
||||||
- [x] Tests assert magenta is ordinary or no longer special.
|
|
||||||
- [x] Tests assert 4096-byte palette blocks where payload size is checked.
|
|
||||||
- [x] Packer test fixtures no longer rely on `convertedRgb565`.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Depends on `PLN-0082`, `PLN-0083`, and `PLN-0084`.
|
|
||||||
|
|
||||||
## Risks
|
|
||||||
|
|
||||||
- Some stale generated fixture data may be easier to regenerate than hand-edit.
|
|
||||||
- Overbroad residue checks could flag historical discussion artifacts; scope
|
|
||||||
checks to normal specs, code, tests, and fixtures.
|
|
||||||
@@ -1,159 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0086
|
|
||||||
ticket: studio-packer-rgba8888-asset-pipeline
|
|
||||||
title: RGBA8888 Final Integration and Residue Removal
|
|
||||||
status: done
|
|
||||||
created: 2026-05-23
|
|
||||||
completed: 2026-05-23
|
|
||||||
ref_decisions:
|
|
||||||
- DEC-0037
|
|
||||||
tags:
|
|
||||||
- integration
|
|
||||||
- validation
|
|
||||||
- residue-removal
|
|
||||||
- rgba8888
|
|
||||||
---
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Run final integration checks and remove normal-path RGB565 residue after the
|
|
||||||
spec, model, emission, projection, and test plans are implemented.
|
|
||||||
|
|
||||||
## Background
|
|
||||||
|
|
||||||
`DEC-0037` prohibits RGB565 compatibility mode, normal `convertedRgb565`
|
|
||||||
projection, magenta color-key behavior, reserved palette index `0`, and partial
|
|
||||||
alpha flattening. Final validation must prove that the repository implements
|
|
||||||
those constraints coherently.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
### Included
|
|
||||||
|
|
||||||
- Repository-wide residue audit.
|
|
||||||
- Full relevant Gradle test execution.
|
|
||||||
- Discussion workflow validation.
|
|
||||||
- Final implementation notes for follow-up plan or lesson creation.
|
|
||||||
|
|
||||||
### Excluded
|
|
||||||
|
|
||||||
- New feature design.
|
|
||||||
- Runtime repository changes.
|
|
||||||
- Variable palette-count work in `DSC-0005`.
|
|
||||||
- Manual regeneration of `main` and `fragments`.
|
|
||||||
|
|
||||||
## Execution Steps
|
|
||||||
|
|
||||||
### Step 1 - Run focused residue searches
|
|
||||||
|
|
||||||
**What:** Find stale RGB565 palette-contract residue.
|
|
||||||
|
|
||||||
**How:** Search production specs/code/tests/fixtures for:
|
|
||||||
`convertedRgb565`, `originalArgb8888`, `RGB565`, `rgb565`, `COLOR_KEY`,
|
|
||||||
`magenta`, `2048`, `indices 1..15`, and partial-alpha flattening text.
|
|
||||||
Classify each match as removed, historical discussion-only, or out-of-scope.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `docs/specs/packer/**`
|
|
||||||
- `docs/specs/studio/**`
|
|
||||||
- `prometeu-packer/**`
|
|
||||||
|
|
||||||
### Step 2 - Run packer tests
|
|
||||||
|
|
||||||
**What:** Execute the packer test suite.
|
|
||||||
|
|
||||||
**How:** Run the Gradle test task that covers `prometeu-packer-v1` and related
|
|
||||||
API modules.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- Gradle modules under `prometeu-packer`
|
|
||||||
|
|
||||||
### Step 3 - Run broader build validation
|
|
||||||
|
|
||||||
**What:** Verify Studio build integration still compiles.
|
|
||||||
|
|
||||||
**How:** Run the repository's standard build or the narrowest existing Gradle
|
|
||||||
task that compiles Studio plus packer consumers.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- Root Gradle project
|
|
||||||
- `prometeu-app`
|
|
||||||
- `prometeu-packer`
|
|
||||||
|
|
||||||
### Step 4 - Validate discussion workflow
|
|
||||||
|
|
||||||
**What:** Ensure discussion artifacts remain consistent.
|
|
||||||
|
|
||||||
**How:** Run `discussion validate` after implementation and before any
|
|
||||||
housekeeping.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- `discussion/index.ndjson`
|
|
||||||
- `discussion/workflow/**`
|
|
||||||
|
|
||||||
### Step 5 - Record remaining intentional residue
|
|
||||||
|
|
||||||
**What:** Document any allowed remaining RGB565 references.
|
|
||||||
|
|
||||||
**How:** If matches remain only in historical discussions, runtime references,
|
|
||||||
or explicit future migration notes, list them in the implementation summary so
|
|
||||||
housekeeping and lesson work can distinguish intentional context from missed
|
|
||||||
normal-path behavior.
|
|
||||||
|
|
||||||
**File(s):**
|
|
||||||
|
|
||||||
- Implementation summary or future lesson, after code work is complete.
|
|
||||||
|
|
||||||
## Test Requirements
|
|
||||||
|
|
||||||
### Unit Tests
|
|
||||||
|
|
||||||
- Packer unit tests must pass.
|
|
||||||
|
|
||||||
### Integration Tests
|
|
||||||
|
|
||||||
- Packer workspace build/materialization tests must pass.
|
|
||||||
- Studio compile/build validation must pass.
|
|
||||||
|
|
||||||
### Manual Verification
|
|
||||||
|
|
||||||
- Residue search results must contain no normal-path `convertedRgb565`,
|
|
||||||
RGB565 glyph palette payload, magenta color-key, reserved index `0`, or
|
|
||||||
partial-alpha flattening behavior.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- [x] `discussion validate` passes.
|
|
||||||
- [x] Packer tests pass.
|
|
||||||
- [x] Studio/packer build validation passes.
|
|
||||||
- [x] Normal specs/code/tests/fixtures contain no stale RGB565 glyph-palette
|
|
||||||
contract residue.
|
|
||||||
- [x] Remaining stale-looking matches, if any, are documented as historical or
|
|
||||||
explicitly out of scope.
|
|
||||||
- [x] `DSC-0005` remains untouched except by explicit future work.
|
|
||||||
|
|
||||||
## Execution Notes
|
|
||||||
|
|
||||||
- `discussion validate` passed.
|
|
||||||
- `./gradlew build` passed.
|
|
||||||
- Residue search found only:
|
|
||||||
- normative spec statements explicitly saying `convertedRgb565` and magenta
|
|
||||||
color-key behavior are not normal contract;
|
|
||||||
- `test-projects/main` asset manifests, which are intentionally out of scope
|
|
||||||
for this implementation because they will be regenerated manually later.
|
|
||||||
- `DSC-0005` was not modified.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Depends on `PLN-0081` through `PLN-0085`.
|
|
||||||
|
|
||||||
## Risks
|
|
||||||
|
|
||||||
- A broad residue search may include historical discussions and cause false
|
|
||||||
positives.
|
|
||||||
- Generated project cache files may change during tests; those changes must be
|
|
||||||
reviewed separately from source edits.
|
|
||||||
@@ -76,10 +76,18 @@ Mandatory declaration metadata on required declaration nodes includes:
|
|||||||
2. declared signature/surface when applicable (parameters/return),
|
2. declared signature/surface when applicable (parameters/return),
|
||||||
3. declaration-level syntactic flags/attributes required by later phases,
|
3. declaration-level syntactic flags/attributes required by later phases,
|
||||||
4. stable `file/start/end` attribution,
|
4. stable `file/start/end` attribution,
|
||||||
5. lifecycle-marker metadata when a declaration carries `[Init]` or `[Frame]`.
|
5. lifecycle-marker metadata when a declaration carries `[Init]` or `[Frame]`,
|
||||||
|
6. documentation attribute metadata when a declaration carries `[Doc(markdown = """...""")]`.
|
||||||
|
|
||||||
Missing required attribution or metadata on mandatory nodes is non-conformant.
|
Missing required attribution or metadata on mandatory nodes is non-conformant.
|
||||||
|
|
||||||
|
Documentation metadata rules:
|
||||||
|
|
||||||
|
- The AST MUST preserve the `Doc` attribute name, the `markdown` argument name, the raw documentation text block payload, and source attribution for the whole attribute and payload.
|
||||||
|
- The AST MUST distinguish documentation text block payloads from ordinary string literals.
|
||||||
|
- The AST MUST preserve enough attribution for later diagnostics to point at malformed or invalid `Doc` usage.
|
||||||
|
- AST construction MUST NOT normalize documentation text block content in a way that loses source-observable parse meaning before the semantic normalization step.
|
||||||
|
|
||||||
## 8. Mandatory Declaration Families
|
## 8. Mandatory Declaration Families
|
||||||
|
|
||||||
The v1 AST must represent, at minimum, declaration families for:
|
The v1 AST must represent, at minimum, declaration families for:
|
||||||
@@ -104,6 +112,8 @@ Lifecycle-observable declarations must preserve marker metadata explicitly:
|
|||||||
- top-level `fn` marked with `[Frame]`,
|
- top-level `fn` marked with `[Frame]`,
|
||||||
- and host method signatures marked with `[InitAllowed]`.
|
- and host method signatures marked with `[InitAllowed]`.
|
||||||
|
|
||||||
|
Documentation-observable declarations must preserve `Doc` metadata explicitly on every accepted named API declaration surface that carries `[Doc(markdown = """...""")]`.
|
||||||
|
|
||||||
## 9. Mandatory Statement and Expression Families
|
## 9. Mandatory Statement and Expression Families
|
||||||
|
|
||||||
The v1 AST must represent statement/expression families for the supported core syntax slice, including at minimum:
|
The v1 AST must represent statement/expression families for the supported core syntax slice, including at minimum:
|
||||||
|
|||||||
@@ -82,7 +82,8 @@ The following inputs are already fixed elsewhere and must not be contradicted he
|
|||||||
- Stable source span metadata is required at the token level and must remain useful to later diagnostics.
|
- Stable source span metadata is required at the token level and must remain useful to later diagnostics.
|
||||||
- Traps are fatal runtime outcomes rather than a recoverable userland diagnostic flow.
|
- Traps are fatal runtime outcomes rather than a recoverable userland diagnostic flow.
|
||||||
- Qualitative cost facts such as retention-bearing operations and host-boundary crossings are normative, but quantitative performance metrics are not.
|
- Qualitative cost facts such as retention-bearing operations and host-boundary crossings are normative, but quantitative performance metrics are not.
|
||||||
- Topic `19` requires deterministic diagnostics for globals, lifecycle markers, init admission, and published-wrapper structural failures.
|
- PBS requires deterministic diagnostics for source-form globals, lifecycle markers, and init admission.
|
||||||
|
- Published-wrapper, boot-guard, synthetic-origin, and invalid-lifecycle-declaration failures are compiler-general. See `docs/specs/compiler/19. Verification and Safety Checks Specification.md` section 11 and `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`.
|
||||||
|
|
||||||
## 6. Required Diagnostic Phases
|
## 6. Required Diagnostic Phases
|
||||||
|
|
||||||
@@ -97,6 +98,8 @@ PBS-facing tooling must distinguish at least the following external diagnostic p
|
|||||||
|
|
||||||
`linking` is a first-class phase in the external diagnostics contract and must not be collapsed away into a generic resolution bucket.
|
`linking` is a first-class phase in the external diagnostics contract and must not be collapsed away into a generic resolution bucket.
|
||||||
|
|
||||||
|
The `host-binding/capability admission` phase covers the source shape of `[Host]` and `[Capability]`. Canonical host-binding identity and capability consistency over `IRReservedMetadata` are platform-owned and are not moved by this specification.
|
||||||
|
|
||||||
This document does not require one finer-grained public phase split for verifier internals, artifact offsets, or transport-specific backend stages beyond what is stated here.
|
This document does not require one finer-grained public phase split for verifier internals, artifact offsets, or transport-specific backend stages beyond what is stated here.
|
||||||
|
|
||||||
## 7. Required Diagnostic Identity, Payload, and Attribution
|
## 7. Required Diagnostic Identity, Payload, and Attribution
|
||||||
@@ -180,7 +183,7 @@ At minimum, the PBS diagnostics baseline must cover:
|
|||||||
5. malformed, unauthorized, or capability-rejected host usage required by `6.2. Host ABI Binding and Loader Resolution Specification.md` and `7. Cartridge Manifest and Runtime Capabilities Specification.md`,
|
5. malformed, unauthorized, or capability-rejected host usage required by `6.2. Host ABI Binding and Loader Resolution Specification.md` and `7. Cartridge Manifest and Runtime Capabilities Specification.md`,
|
||||||
6. source-attributable backend-originated failures that remain user-actionable under normative lowering or load-facing rules.
|
6. source-attributable backend-originated failures that remain user-actionable under normative lowering or load-facing rules.
|
||||||
7. dependency-scoped fail-fast admission at frontend boundary: when one module is rejected, modules that import it (directly or transitively) must not be emitted, while diagnostics collection for independent modules must continue.
|
7. dependency-scoped fail-fast admission at frontend boundary: when one module is rejected, modules that import it (directly or transitively) must not be emitted, while diagnostics collection for independent modules must continue.
|
||||||
8. lifecycle and globals diagnostics required by topic `19`, including:
|
8. lifecycle-marker and source-form global diagnostics, including:
|
||||||
- `global initializer uses unsupported form`,
|
- `global initializer uses unsupported form`,
|
||||||
- `global dependency cycle detected`,
|
- `global dependency cycle detected`,
|
||||||
- `global import must resolve through a global barrel entry`,
|
- `global import must resolve through a global barrel entry`,
|
||||||
@@ -194,16 +197,13 @@ At minimum, the PBS diagnostics baseline must cover:
|
|||||||
- `project init must be colocated with frame`,
|
- `project init must be colocated with frame`,
|
||||||
- `Init attribute target invalid`,
|
- `Init attribute target invalid`,
|
||||||
- `InitAllowed is valid only on SDK host methods`,
|
- `InitAllowed is valid only on SDK host methods`,
|
||||||
- `host call not allowed during init`,
|
- `host call not allowed during init`.
|
||||||
- `synthetic wrapper entrypoint missing`,
|
9. compiler-general lifecycle-assembly and IRVM-precondition failures, which this PBS catalog MUST NOT claim as PBS required coverage; see `docs/specs/compiler/19. Verification and Safety Checks Specification.md` section 11 and `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`.
|
||||||
- `published entrypoint is not function index 0`,
|
10. symbolic asset-reference diagnostics required by backend-owned `Addressable` resolution, including:
|
||||||
- `hidden boot guard is missing`,
|
|
||||||
- `synthetic callable origin missing`.
|
|
||||||
9. symbolic asset-reference diagnostics required by backend-owned `Addressable` resolution, including:
|
|
||||||
- unresolved terminal asset reference,
|
- unresolved terminal asset reference,
|
||||||
- namespace-versus-terminal asset misuse,
|
- namespace-versus-terminal asset misuse,
|
||||||
- structurally invalid symbolic asset path admitted by source syntax but rejected by semantic surface rules.
|
- structurally invalid symbolic asset path admitted by source syntax but rejected by semantic surface rules.
|
||||||
10. ignored-value diagnostics for expression statements, including:
|
11. ignored-value diagnostics for expression statements, including:
|
||||||
- a stable warning when a materialized value is produced and then ignored,
|
- a stable warning when a materialized value is produced and then ignored,
|
||||||
- and no warning for unit-like expression statements.
|
- and no warning for unit-like expression statements.
|
||||||
|
|
||||||
@@ -214,6 +214,19 @@ Reserved-attribute diagnostics for host-backed asset lowering must also cover:
|
|||||||
- out-of-range `AssetLowering.param` indexes,
|
- out-of-range `AssetLowering.param` indexes,
|
||||||
- and `AssetLowering` targets whose selected parameter is not statically typed as `Addressable`.
|
- and `AssetLowering` targets whose selected parameter is not statically typed as `Addressable`.
|
||||||
|
|
||||||
|
Documentation attribute diagnostics must cover:
|
||||||
|
|
||||||
|
- unterminated documentation text block syntax,
|
||||||
|
- `Doc` used without the required `markdown` argument,
|
||||||
|
- `Doc` with extra or unknown arguments,
|
||||||
|
- `Doc` with a non-documentation-text-block payload,
|
||||||
|
- duplicate `Doc` on the same declaration,
|
||||||
|
- `Doc` applied to a parameter or other non-documentable surface,
|
||||||
|
- normalized empty or whitespace-only documentation payload,
|
||||||
|
- and rejected aliases or alternate forms such as `text`, positional arguments, `html`, `format`, `Document`, `Documentation`, or `md"""..."""`.
|
||||||
|
|
||||||
|
Diagnostics for duplicate `Doc` attributes must be static semantic diagnostics and should include a related site for the conflicting declaration attribute when available.
|
||||||
|
|
||||||
At minimum, host-admission diagnostics must cover missing or malformed host capability metadata and unknown or undeclared capability names.
|
At minimum, host-admission diagnostics must cover missing or malformed host capability metadata and unknown or undeclared capability names.
|
||||||
|
|
||||||
Only backend-originated failures that remain source-attributable and user-actionable belong to the PBS-facing diagnostics contract.
|
Only backend-originated failures that remain source-attributable and user-actionable belong to the PBS-facing diagnostics contract.
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
# PBS Lowering IRBackend Specification
|
# PBS Lowering IRBackend Specification
|
||||||
|
|
||||||
Status: Draft v1 (Frontend Scope + Backend Handoff Addendum)
|
Status: Draft v1 (PBS Frontend Scope + Common Handoff Emission)
|
||||||
Applies to: first lowering boundary from bound PBS frontend model into `IRBackend`/`IRBackendFile`, plus executable-backend handoff obligations at this boundary
|
Applies to: first lowering boundary from bound PBS frontend model into the common `IRBackend`/`IRBackendFile` handoff
|
||||||
|
|
||||||
## 1. Purpose
|
## 1. Purpose
|
||||||
|
|
||||||
This document defines the normative frontend lowering contract from PBS source semantics to `IRBackend`.
|
This document defines the normative frontend lowering contract from PBS source semantics to the common `IRBackend` handoff.
|
||||||
|
|
||||||
Its purpose is to keep the first lowering deterministic and shared across implementations while PBS and backend design evolve.
|
Its purpose is to keep PBS lowering deterministic while preserving the common frontend-to-backend contract owned by compiler-general backend specs.
|
||||||
|
|
||||||
## 2. Scope
|
## 2. Scope
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ This document defines:
|
|||||||
- semantic obligations preserved in `IRBackend`,
|
- semantic obligations preserved in `IRBackend`,
|
||||||
- deterministic rejection behavior for unsupported frontend-lowering forms,
|
- deterministic rejection behavior for unsupported frontend-lowering forms,
|
||||||
- diagnostics attribution obligations for lowering failures in frontend scope,
|
- diagnostics attribution obligations for lowering failures in frontend scope,
|
||||||
- executable-backend handoff obligations at the `IRBackend` boundary,
|
- PBS obligations for emitting the common executable `IRBackend` handoff,
|
||||||
- and backend-owned symbolic lowering obligations for asset-facing references.
|
- and backend-owned symbolic lowering obligations for asset-facing references.
|
||||||
|
|
||||||
This document does not define:
|
This document does not define:
|
||||||
@@ -26,7 +26,8 @@ This document does not define:
|
|||||||
- VM lowering (`IRVM`),
|
- VM lowering (`IRVM`),
|
||||||
- bytecode/PBX mapping,
|
- bytecode/PBX mapping,
|
||||||
- runtime execution behavior,
|
- runtime execution behavior,
|
||||||
- verifier/loader internals.
|
- verifier/loader internals,
|
||||||
|
- or common backend ownership of the `IRBackend -> IRVM` contract.
|
||||||
|
|
||||||
Those concerns belong to shared acceptance specs under `docs/specs/compiler`.
|
Those concerns belong to shared acceptance specs under `docs/specs/compiler`.
|
||||||
|
|
||||||
@@ -75,9 +76,9 @@ When the active source slice depends on a backend-owned symbolic surface such as
|
|||||||
- the frontend must not query domain services directly to discover operational assets;
|
- the frontend must not query domain services directly to discover operational assets;
|
||||||
- and lowering must preserve enough identity for the backend to complete final operational resolution.
|
- and lowering must preserve enough identity for the backend to complete final operational resolution.
|
||||||
|
|
||||||
## 6. IRBackend Preserved Obligations
|
## 6. PBS IRBackend Emission Obligations
|
||||||
|
|
||||||
For each admitted source unit and callable in the current lowering slice, `IRBackend` must preserve at minimum:
|
For each admitted PBS source unit and callable in the current lowering slice, PBS lowering must emit `IRBackend` that preserves at minimum:
|
||||||
|
|
||||||
1. callable identity (name/category as applicable),
|
1. callable identity (name/category as applicable),
|
||||||
2. callable arity,
|
2. callable arity,
|
||||||
@@ -85,14 +86,18 @@ For each admitted source unit and callable in the current lowering slice, `IRBac
|
|||||||
4. source attribution anchor (`file + span`) for diagnostics and traceability,
|
4. source attribution anchor (`file + span`) for diagnostics and traceability,
|
||||||
5. source-observable parse intent for statement/expression structure (including precedence/associativity outcome already fixed by AST shape).
|
5. source-observable parse intent for statement/expression structure (including precedence/associativity outcome already fixed by AST shape).
|
||||||
6. deterministic `requiredCapabilities` derived from admitted host-binding metadata for packer/runtime-manifest assistance.
|
6. deterministic `requiredCapabilities` derived from admitted host-binding metadata for packer/runtime-manifest assistance.
|
||||||
7. compiler-selected published-wrapper entrypoint identity for backend handoff,
|
7. a typed `IRLifecycleDeclaration` for executable programs, with file-init fragment, optional project-init, and required frame-root references,
|
||||||
8. explicit global and synthetic lifecycle structure required by executable lowering.
|
8. explicit user globals and frontend-lowered file-init fragments required by later common lifecycle assembly,
|
||||||
9. backend-owned symbolic identities that must survive to later executable lowering, including symbolic asset references when admitted by the source slice.
|
9. backend-owned symbolic identities that must survive to later executable lowering, including symbolic asset references when admitted by the source slice.
|
||||||
|
|
||||||
|
PBS lowering MUST NOT emit module init, project-init wrapper, published frame wrapper, physical entrypoint, or boot guard. Those artifacts are produced exclusively by common lifecycle assembly.
|
||||||
|
|
||||||
Lowering must not collapse source categories in a way that erases required declaration/callable identity needed by downstream diagnostics or conformance assertions.
|
Lowering must not collapse source categories in a way that erases required declaration/callable identity needed by downstream diagnostics or conformance assertions.
|
||||||
|
|
||||||
The normative contract is obligation-based, not tied to one mandatory in-memory class graph.
|
The normative contract is obligation-based, not tied to one mandatory in-memory class graph.
|
||||||
|
|
||||||
|
`IRBackend` itself is the common frontend-to-backend executable handoff. This PBS spec owns only the PBS-specific admission and translation path into that handoff. Common backend rules for consuming `IRBackend` are owned by `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`.
|
||||||
|
|
||||||
## 7. Deterministic Rejection Policy
|
## 7. Deterministic Rejection Policy
|
||||||
|
|
||||||
If a source form is outside current frontend-lowering support:
|
If a source form is outside current frontend-lowering support:
|
||||||
@@ -111,7 +116,7 @@ For multi-module builds, lowering admission must apply dependency-scoped fail-fa
|
|||||||
|
|
||||||
## 8. Conformance Boundary
|
## 8. Conformance Boundary
|
||||||
|
|
||||||
`IRBackend` is the first lowering boundary (frontend responsibility).
|
PBS emission into `IRBackend` is the first PBS lowering boundary (frontend responsibility).
|
||||||
|
|
||||||
Conformance-valid claims at this boundary require Gate U evidence from `docs/specs/compiler/13. Conformance Test Specification.md`.
|
Conformance-valid claims at this boundary require Gate U evidence from `docs/specs/compiler/13. Conformance Test Specification.md`.
|
||||||
|
|
||||||
@@ -148,9 +153,9 @@ This document is healthy when:
|
|||||||
3. deterministic rejection policy is explicit and test-backed,
|
3. deterministic rejection policy is explicit and test-backed,
|
||||||
4. and scope boundaries with general/backend acceptance specs are explicit.
|
4. and scope boundaries with general/backend acceptance specs are explicit.
|
||||||
|
|
||||||
## 12. Executable Backend Handoff Addendum (v1)
|
## 12. PBS Executable Handoff Emission Obligations (v1)
|
||||||
|
|
||||||
For executable backends, the `IRBackend` output from this frontend boundary must satisfy the additional handoff obligations below.
|
For executable backends, PBS lowering must emit `IRBackend` satisfying the additional handoff obligations below before common backend lowering starts.
|
||||||
|
|
||||||
### 12.1 Callable obligations
|
### 12.1 Callable obligations
|
||||||
|
|
||||||
@@ -170,7 +175,7 @@ Each executable callsite in `IRBackend` must be classified into exactly one cate
|
|||||||
2. `CALL_HOST`,
|
2. `CALL_HOST`,
|
||||||
3. `CALL_INTRINSIC`.
|
3. `CALL_INTRINSIC`.
|
||||||
|
|
||||||
Backend lowering must not infer this category by textual heuristics.
|
PBS lowering must not leave this category for backend inference by textual heuristics.
|
||||||
|
|
||||||
### 12.3 Host-backed metadata obligations
|
### 12.3 Host-backed metadata obligations
|
||||||
|
|
||||||
@@ -187,11 +192,11 @@ When a host-backed callsite also depends on backend-owned symbolic asset lowerin
|
|||||||
- the frontend boundary MUST preserve which callsite argument is asset-facing;
|
- the frontend boundary MUST preserve which callsite argument is asset-facing;
|
||||||
- for PBS v1 this asset-facing designation is carried by reserved host metadata `[AssetLowering(param = N)]`;
|
- for PBS v1 this asset-facing designation is carried by reserved host metadata `[AssetLowering(param = N)]`;
|
||||||
- the preserved symbolic operand MUST remain attributable to a backend-provided `Addressable` identity;
|
- the preserved symbolic operand MUST remain attributable to a backend-provided `Addressable` identity;
|
||||||
- backend stages MUST be able to rewrite that symbolic operand into runtime-facing `asset_id` before the final low-level host path is emitted.
|
- common backend stages MUST be able to rewrite that symbolic operand into runtime-facing `asset_id` before the final low-level host path is emitted.
|
||||||
|
|
||||||
When an expression statement leaves a materialized runtime value on the stack:
|
When an expression statement leaves a materialized runtime value on the stack:
|
||||||
|
|
||||||
- `IRBackend` lowering MUST emit explicit discard behavior rather than relying on implicit backend stack cleanup;
|
- PBS lowering into `IRBackend` MUST emit explicit discard behavior rather than relying on implicit backend stack cleanup;
|
||||||
- for single-slot materialized values this discard is represented by `POP`;
|
- for single-slot materialized values this discard is represented by `POP`;
|
||||||
- and the discard path MUST preserve stack-accounting validity for subsequent backend lowering stages.
|
- and the discard path MUST preserve stack-accounting validity for subsequent backend lowering stages.
|
||||||
|
|
||||||
@@ -218,20 +223,18 @@ It does not replace:
|
|||||||
2. `docs/specs/compiler/21. IRVM Optimization Pipeline Specification.md`,
|
2. `docs/specs/compiler/21. IRVM Optimization Pipeline Specification.md`,
|
||||||
3. or `docs/specs/compiler/15. Bytecode and PBX Mapping Specification.md`.
|
3. or `docs/specs/compiler/15. Bytecode and PBX Mapping Specification.md`.
|
||||||
|
|
||||||
### 12.7 Executable Lifecycle and Published Wrapper Obligation
|
### 12.7 Executable Lifecycle Declaration Obligation
|
||||||
|
|
||||||
For executable PBS frontends, backend handoff must preserve the compiler-selected published wrapper rather than a frontend-declared nominal entrypoint.
|
For executable PBS frontends, PBS lowering MUST emit a typed `IRLifecycleDeclaration` rather than assembling the published lifecycle.
|
||||||
|
|
||||||
At `IRBackend` emission time:
|
At frontend `IRBackend` emission time:
|
||||||
|
|
||||||
1. the lowered graph must contain explicit lifecycle structure for:
|
1. PBS MUST retain marker admission for `[Init]`, `[Frame]`, and `InitAllowed`,
|
||||||
- user-authored globals,
|
2. PBS MUST emit typed references for:
|
||||||
- file init fragments,
|
- file-init fragments that include global materialization and non-project `[Init]`,
|
||||||
- module init,
|
- the optional project-init callable, which is the `[Init]` colocated with `[Frame]`,
|
||||||
- project init when present,
|
- and the required frame-root callable marked with `[Frame]`,
|
||||||
- and the published frame wrapper,
|
3. the colocated project init MUST be excluded from file-init fragments,
|
||||||
2. the published frame wrapper must be the effective entrypoint identity handed to backend stages,
|
4. module order in the declaration MUST propagate the explicit dependency order already derived from resolved project/module data, without sorting by `FileId`, textual module name, or synthetic callable name,
|
||||||
3. the userland callable marked with `[Frame]` must remain distinguishable as the logical frame root,
|
5. PBS MUST NOT emit module init, project-init wrapper, published frame wrapper, physical entrypoint, or boot guard,
|
||||||
4. the wrapper must own final `FRAME_RET`,
|
6. and common lifecycle assembly remains the owner of derived artifacts, including the published wrapper that becomes the physical entrypoint and owns the final frame return.
|
||||||
5. backend stages must not reintroduce manifest-owned or `FrontendSpec`-owned nominal entrypoint authority,
|
|
||||||
6. and hidden compiler-owned lifecycle state such as the boot guard must remain structurally distinguishable from user globals.
|
|
||||||
|
|||||||
@@ -114,6 +114,13 @@ String literals:
|
|||||||
- delimited by `"`.
|
- delimited by `"`.
|
||||||
- supported escapes: `\\`, `\"`, `\n`, `\r`, `\t`.
|
- supported escapes: `\\`, `\"`, `\n`, `\r`, `\t`.
|
||||||
|
|
||||||
|
Documentation text block literals:
|
||||||
|
|
||||||
|
- delimited by `"""`.
|
||||||
|
- valid only as the value of the `markdown` argument in the reserved `[Doc(markdown = """...""")]` attribute surface.
|
||||||
|
- not part of the runtime expression literal surface in v1 core.
|
||||||
|
- preserve authored text for later documentation normalization.
|
||||||
|
|
||||||
Boolean literals:
|
Boolean literals:
|
||||||
|
|
||||||
- `true`, `false`.
|
- `true`, `false`.
|
||||||
@@ -241,7 +248,8 @@ Attribute ::= '[' Identifier AttrArgs? ']'
|
|||||||
AttrArgs ::= '(' AttrArgList? ')'
|
AttrArgs ::= '(' AttrArgList? ')'
|
||||||
AttrArgList ::= AttrArg (',' AttrArg)*
|
AttrArgList ::= AttrArg (',' AttrArg)*
|
||||||
AttrArg ::= Identifier '=' AttrValue
|
AttrArg ::= Identifier '=' AttrValue
|
||||||
AttrValue ::= StringLit | IntLit | BoolLit
|
AttrValue ::= StringLit | IntLit | BoolLit | DocTextBlock
|
||||||
|
DocTextBlock ::= '"""' DocTextBlockChar* '"""'
|
||||||
```
|
```
|
||||||
|
|
||||||
Rules:
|
Rules:
|
||||||
@@ -250,11 +258,16 @@ Rules:
|
|||||||
- Attributes do not introduce values, types, callables, or modules by themselves.
|
- Attributes do not introduce values, types, callables, or modules by themselves.
|
||||||
- In v1 core, ordinary user-authored modules MUST reject attributes unless another specification explicitly permits them.
|
- In v1 core, ordinary user-authored modules MUST reject attributes unless another specification explicitly permits them.
|
||||||
- Ordinary userland source MAY use `[Init]` and `[Frame]` only on top-level `fn` declarations.
|
- Ordinary userland source MAY use `[Init]` and `[Frame]` only on top-level `fn` declarations.
|
||||||
|
- Ordinary userland source MAY use `[Doc(markdown = """...""")]` on named API declarations where the static semantics specification permits documentation.
|
||||||
- Reserved stdlib/toolchain interface modules MAY use attributes where explicitly allowed by syntax and semantics.
|
- Reserved stdlib/toolchain interface modules MAY use attributes where explicitly allowed by syntax and semantics.
|
||||||
- Reserved stdlib/toolchain interface modules MAY additionally use `[InitAllowed]` only on `declare host` method signatures where another specification explicitly permits it.
|
- Reserved stdlib/toolchain interface modules MAY additionally use `[InitAllowed]` only on `declare host` method signatures where another specification explicitly permits it.
|
||||||
- Attribute interpretation is compile-time only unless another specification explicitly lowers its effect into runtime-facing metadata.
|
- Attribute interpretation is compile-time only unless another specification explicitly lowers its effect into runtime-facing metadata.
|
||||||
- Reserved attribute names used by builtin-type and intrinsic shells do not become ordinary value-level syntax.
|
- Reserved attribute names used by builtin-type and intrinsic shells do not become ordinary value-level syntax.
|
||||||
- `Slot(...)` is not part of the v1 attribute surface; source that uses `Slot` must be rejected in syntax phase.
|
- `Slot(...)` is not part of the v1 attribute surface; source that uses `Slot` must be rejected in syntax phase.
|
||||||
|
- `Doc` is a reserved documentation attribute name. Its only v1 syntactic shape is `[Doc(markdown = """...""")]`.
|
||||||
|
- The `Doc` attribute MUST NOT accept positional arguments, `text`, `html`, `format`, `Document`, `Documentation`, or prefixed text block forms such as `md"""..."""`.
|
||||||
|
- Documentation text blocks are not string literals and MUST NOT appear in ordinary expressions, parameter defaults, or non-`Doc` attribute arguments.
|
||||||
|
- Attribute ordering is syntactically insignificant; semantic validation determines duplicate or invalid attribute combinations.
|
||||||
|
|
||||||
### 6.2 Top-level declarations
|
### 6.2 Top-level declarations
|
||||||
|
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ Rules:
|
|||||||
- Attributes are not first-class values and are not reflectable in v1 core.
|
- Attributes are not first-class values and are not reflectable in v1 core.
|
||||||
- Attributes do not automatically survive into runtime or bytecode artifacts.
|
- Attributes do not automatically survive into runtime or bytecode artifacts.
|
||||||
- An attribute affects runtime artifacts only when another specification defines an explicit lowering for its semantic effect.
|
- An attribute affects runtime artifacts only when another specification defines an explicit lowering for its semantic effect.
|
||||||
- In v1 core, the normative reserved attributes are `Host`, `Capability`, `AssetLowering`, `BuiltinType`, `BuiltinConst`, `IntrinsicCall`, `Init`, `Frame`, and `InitAllowed`.
|
- In v1 core, the normative reserved attributes are `Host`, `Capability`, `AssetLowering`, `BuiltinType`, `BuiltinConst`, `IntrinsicCall`, `Init`, `Frame`, `InitAllowed`, and `Doc`.
|
||||||
- `Host` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
|
- `Host` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
|
||||||
- `Capability` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
|
- `Capability` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
|
||||||
- `AssetLowering` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
|
- `AssetLowering` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
|
||||||
@@ -100,6 +100,42 @@ Rules:
|
|||||||
- Builtin metadata is consumed by the compiler during VM-owned builtin and intrinsic lowering rather than by host-binding lowering.
|
- Builtin metadata is consumed by the compiler during VM-owned builtin and intrinsic lowering rather than by host-binding lowering.
|
||||||
- `Init` and `Frame` are consumed by lifecycle analysis and lowering rather than by ordinary runtime reflection.
|
- `Init` and `Frame` are consumed by lifecycle analysis and lowering rather than by ordinary runtime reflection.
|
||||||
- `InitAllowed` is consumed by init-time host-admission analysis and does not become ordinary userland metadata.
|
- `InitAllowed` is consumed by init-time host-admission analysis and does not become ordinary userland metadata.
|
||||||
|
- `Doc` is compile/editor documentation metadata and is consumed by compiler-owned editorial surfaces.
|
||||||
|
- `Doc` MUST NOT be lowered into bytecode, PBX, cartridge, or runtime-facing artifacts unless a future specification explicitly defines such lowering.
|
||||||
|
|
||||||
|
### 2.3.1 `Doc` documentation metadata
|
||||||
|
|
||||||
|
`Doc` attaches authored Markdown documentation to a named API declaration.
|
||||||
|
|
||||||
|
Canonical v1 shape:
|
||||||
|
|
||||||
|
```pbs
|
||||||
|
[Doc(markdown = """
|
||||||
|
Draws a sprite.
|
||||||
|
|
||||||
|
- `x`: screen x
|
||||||
|
- `y`: screen y
|
||||||
|
""")]
|
||||||
|
```
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- `Doc` MUST declare exactly one named argument, `markdown`.
|
||||||
|
- `Doc.markdown` MUST be a documentation text block.
|
||||||
|
- `Doc` MUST NOT accept aliases or alternate forms such as `text`, positional arguments, `html`, `format`, `Document`, `Documentation`, or `md"""..."""`.
|
||||||
|
- A declaration MUST NOT carry more than one `Doc` attribute.
|
||||||
|
- Duplicate `Doc` attributes are static semantic errors and must not be rejected only as parser errors.
|
||||||
|
- Attribute order is semantically irrelevant; `Doc` colocated with other valid attributes has the same meaning regardless of ordering.
|
||||||
|
- `Doc` is valid only on named API declarations that introduce named semantic symbols and can carry attributes.
|
||||||
|
- The v1 documentable surface includes functions, methods, classes/structs when present, services, hosts, builtin and stdlib declarations, and interface declarations.
|
||||||
|
- Parameters MUST NOT receive `Doc` in v1. Parameter documentation, when present, MUST be authored inside the Markdown payload of the owning declaration.
|
||||||
|
- Fields, enum cases, tuple fields, local variables, expressions, and other non-API declaration surfaces MUST NOT receive `Doc` unless a future decision explicitly classifies them as documentable named API declarations.
|
||||||
|
- Documentation text block content MUST be normalized before semantic empty-payload validation and before exposure to editor consumers.
|
||||||
|
- Normalization MUST remove an incidental leading empty line, remove an incidental trailing empty line, compute the common indentation of non-empty content lines, remove that common indentation, preserve internal line breaks, and preserve Markdown content after indentation normalization.
|
||||||
|
- A normalized empty or whitespace-only `Doc.markdown` payload is invalid.
|
||||||
|
- The authored format is a supported Markdown subset. Rendering, sanitization, and unsupported Markdown constructs are consumer responsibilities.
|
||||||
|
- Compiler semantic metadata MUST preserve normalized Markdown documentation as metadata of the documented symbol.
|
||||||
|
- LSP and editor consumers MUST consume compiler-resolved documentation metadata rather than reparsing source text.
|
||||||
|
|
||||||
### 2.4 Tuple shapes
|
### 2.4 Tuple shapes
|
||||||
|
|
||||||
@@ -214,6 +250,8 @@ Rules:
|
|||||||
- A file may declare at most one `[Init]`.
|
- A file may declare at most one `[Init]`.
|
||||||
- The `[Init]` colocated with `[Frame]` is the project init.
|
- The `[Init]` colocated with `[Frame]` is the project init.
|
||||||
- Project init must be colocated with `[Frame]`.
|
- Project init must be colocated with `[Frame]`.
|
||||||
|
- PBS static semantics and lowering admit those markers and translate them into a typed `IRLifecycleDeclaration`.
|
||||||
|
- PBS MUST NOT materialize module init, project-init wrapper, published frame wrapper, physical entrypoint, or boot guard; those artifacts belong to common lifecycle assembly.
|
||||||
- `InitAllowed` is valid only on SDK host methods and is invalid on userland `fn`, `global`, `service`, `const`, `struct`, `contract`, and callback surfaces.
|
- `InitAllowed` is valid only on SDK host methods and is invalid on userland `fn`, `global`, `service`, `const`, `struct`, `contract`, and callback surfaces.
|
||||||
- A host method signature in a reserved stdlib/interface module MUST carry exactly one `Host` attribute.
|
- A host method signature in a reserved stdlib/interface module MUST carry exactly one `Host` attribute.
|
||||||
- A host method signature in a reserved stdlib/interface module MUST carry exactly one `Capability` attribute.
|
- A host method signature in a reserved stdlib/interface module MUST carry exactly one `Capability` attribute.
|
||||||
|
|||||||
+11
@@ -354,6 +354,8 @@ Rules:
|
|||||||
- Renaming a public stdlib or host-backed parameter is API compatibility-sensitive and MUST be reviewed with the same discipline as other public callable-shape changes.
|
- Renaming a public stdlib or host-backed parameter is API compatibility-sensitive and MUST be reviewed with the same discipline as other public callable-shape changes.
|
||||||
- Interface-module loaders MUST NOT replace missing or unavailable public parameter names with generated ordinal placeholders such as `arg0` or `arg1`.
|
- Interface-module loaders MUST NOT replace missing or unavailable public parameter names with generated ordinal placeholders such as `arg0` or `arg1`.
|
||||||
- Missing canonical parameter identity MUST be represented as incomplete semantic metadata, not as a fabricated public name.
|
- Missing canonical parameter identity MUST be represented as incomplete semantic metadata, not as a fabricated public name.
|
||||||
|
- Stdlib, SDK, and interface-module API declarations SHOULD carry authored English documentation through `[Doc(markdown = """...""")]` once the documentation surface is implemented.
|
||||||
|
- Stdlib and SDK parameter documentation MUST be authored inside the owning declaration's Markdown payload; parameters MUST NOT carry `[Doc]`.
|
||||||
|
|
||||||
### 9.3 Interface-module restrictions
|
### 9.3 Interface-module restrictions
|
||||||
|
|
||||||
@@ -441,6 +443,15 @@ Rules:
|
|||||||
- Attributes are not exported as ordinary values, types, or runtime-reflectable objects.
|
- Attributes are not exported as ordinary values, types, or runtime-reflectable objects.
|
||||||
- Attributes do not automatically survive into bytecode, PBX, or runtime metadata.
|
- Attributes do not automatically survive into bytecode, PBX, or runtime metadata.
|
||||||
|
|
||||||
|
`Doc` is a reserved documentation attribute for compiler/editor metadata.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- Stdlib, SDK, and interface modules MUST use the same `[Doc(markdown = """...""")]` surface as ordinary PBS source for authored API documentation.
|
||||||
|
- Authored source documentation takes precedence over imported or generated documentation for the same symbol.
|
||||||
|
- Conflicts between authored and imported/generated documentation MUST be resolved deterministically or reported through explicit diagnostics.
|
||||||
|
- `Doc` metadata enriches compiler/editor surfaces and MUST NOT change import resolution, host binding, ABI identity, executable lowering, or runtime behavior.
|
||||||
|
|
||||||
### 11.2 `Host` attribute
|
### 11.2 `Host` attribute
|
||||||
|
|
||||||
The canonical reserved host-binding attribute is:
|
The canonical reserved host-binding attribute is:
|
||||||
|
|||||||
+17
-6
@@ -15,6 +15,10 @@ This document defines the current contract between:
|
|||||||
Its purpose is to let compiler and runtime work in parallel without diverging on the most critical boundary:
|
Its purpose is to let compiler and runtime work in parallel without diverging on the most critical boundary:
|
||||||
how host-backed SDK calls become load-time-resolved numeric syscalls.
|
how host-backed SDK calls become load-time-resolved numeric syscalls.
|
||||||
|
|
||||||
|
PBS `declare host` / `[Host]` shells are compile-time delivery. The
|
||||||
|
loader-facing catalog is runtime-owned. This document MUST NOT publish syscall
|
||||||
|
IDs or `SyscallMeta`.
|
||||||
|
|
||||||
This document is intentionally narrower than a full PBX or VM specification.
|
This document is intentionally narrower than a full PBX or VM specification.
|
||||||
It focuses on loader behavior and the minimum artifact contract the loader must consume.
|
It focuses on loader behavior and the minimum artifact contract the loader must consume.
|
||||||
|
|
||||||
@@ -44,16 +48,20 @@ This document does not define:
|
|||||||
|
|
||||||
This document follows two prior decisions:
|
This document follows two prior decisions:
|
||||||
|
|
||||||
1. Canonical host identity is defined by the hardware ABI as `(module, name, version)`.
|
1. Canonical host identity is defined by the runtime host registry as `(module, name, version)`.
|
||||||
2. User code does not declare host bindings directly; SDK/toolchain-controlled modules expose reserved `declare host` surfaces and the compiler lowers those usages into PBX host-binding metadata.
|
2. User code does not declare host bindings directly; SDK/toolchain-controlled modules expose reserved `declare host` surfaces and the compiler lowers those usages into PBX host-binding metadata.
|
||||||
|
|
||||||
|
PBS shells MUST repeat identities already published by the runtime registry
|
||||||
|
(`../runtime/docs/specs/runtime/16-host-abi-and-syscalls.md` and `SyscallMeta`).
|
||||||
|
They MUST NOT invent `(module, name, version)`.
|
||||||
|
|
||||||
This document therefore treats:
|
This document therefore treats:
|
||||||
|
|
||||||
- `declare host Gfx { fn draw_pixel(...); }`
|
- `declare host LowGfx { [Host(module = "gfx2d", name = "clear", version = 1)] fn clear(...); }`
|
||||||
|
|
||||||
as compile-time surface only, and treats:
|
as compile-time surface only, and treats:
|
||||||
|
|
||||||
- `("gfx", "draw_pixel", 1)`
|
- `("gfx2d", "clear", 1)`
|
||||||
|
|
||||||
as the normative runtime-facing identity.
|
as the normative runtime-facing identity.
|
||||||
|
|
||||||
@@ -63,7 +71,7 @@ The host-binding pipeline is:
|
|||||||
|
|
||||||
1. User code imports SDK surfaces such as `Gfx` from `@sdk:gfx` and `Composer` from `@sdk:composer`.
|
1. User code imports SDK surfaces such as `Gfx` from `@sdk:gfx` and `Composer` from `@sdk:composer`.
|
||||||
2. The compiler resolves those surfaces against the selected stdlib line.
|
2. The compiler resolves those surfaces against the selected stdlib line.
|
||||||
3. The compiler maps each host-backed SDK member to a canonical identity `(module, name, version)`.
|
3. The compiler maps each host-backed SDK member to a canonical identity `(module, name, version)` that already exists in the runtime host registry.
|
||||||
4. The compiler emits those required canonical identities into the PBX `SYSC` table.
|
4. The compiler emits those required canonical identities into the PBX `SYSC` table.
|
||||||
5. The compiler emits pre-load host call sites as `HOSTCALL <sysc_index>`.
|
5. The compiler emits pre-load host call sites as `HOSTCALL <sysc_index>`.
|
||||||
6. At cartridge load time, the loader resolves `SYSC` entries against the host syscall registry.
|
6. At cartridge load time, the loader resolves `SYSC` entries against the host syscall registry.
|
||||||
@@ -84,7 +92,7 @@ Every host binding is identified by the triple:
|
|||||||
|
|
||||||
Rules:
|
Rules:
|
||||||
|
|
||||||
- `module` is the canonical host subsystem namespace, such as `gfx` or `audio`.
|
- `module` is the canonical host subsystem namespace, such as `gfx2d` or `asset`.
|
||||||
- `name` is the canonical host operation name within that module.
|
- `name` is the canonical host operation name within that module.
|
||||||
- `version` is the canonical ABI version of that host operation.
|
- `version` is the canonical ABI version of that host operation.
|
||||||
- This identity is stable across source languages and SDK naming styles.
|
- This identity is stable across source languages and SDK naming styles.
|
||||||
@@ -310,7 +318,10 @@ Rules:
|
|||||||
- the loader resolves only against this canonical registry,
|
- the loader resolves only against this canonical registry,
|
||||||
- unknown identities are load errors,
|
- unknown identities are load errors,
|
||||||
- successful resolution yields numeric syscall identifiers and associated metadata,
|
- successful resolution yields numeric syscall identifiers and associated metadata,
|
||||||
- the resolved metadata is authoritative for capability gating and later runtime verification.
|
- the resolved metadata is authoritative for capability gating and later runtime verification,
|
||||||
|
- PBS `declare host` / `[Host]` shells MUST repeat identities from this registry,
|
||||||
|
- PBS shells MUST NOT invent `(module, name, version)`,
|
||||||
|
- this specification MUST NOT publish the syscall catalog; runtime spec 16 and `SyscallMeta` do.
|
||||||
|
|
||||||
For the current asset runtime surface, the canonical registry entries include:
|
For the current asset runtime surface, the canonical registry entries include:
|
||||||
|
|
||||||
|
|||||||
+49
-30
@@ -16,7 +16,11 @@ Its purpose is to make the stdlib:
|
|||||||
|
|
||||||
This document complements the normative language-level model in:
|
This document complements the normative language-level model in:
|
||||||
|
|
||||||
- [5. Manifest, Stdlib, and SDK Resolution Specification.md](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/docs/specs/pbs/5.%20Manifest,%20Stdlib,%20and%20SDK%20Resolution%20Specification.md)
|
- [5. Manifest, Stdlib, and SDK Resolution Specification.md](5.%20Manifest%2C%20Stdlib%2C%20and%20SDK%20Resolution%20Specification.md)
|
||||||
|
|
||||||
|
This document is PBS packaging. It MUST NOT define console ABI. Intrinsic
|
||||||
|
`final_id` values and host `SyscallMeta` remain runtime-owned. Physical stdlib
|
||||||
|
path MUST NOT imply VM-owned versus host-backed ownership.
|
||||||
|
|
||||||
## 2. Scope
|
## 2. Scope
|
||||||
|
|
||||||
@@ -53,52 +57,66 @@ The recommended Studio layout is:
|
|||||||
```text
|
```text
|
||||||
prometeu-compiler/frontends/prometeu-frontend-pbs/
|
prometeu-compiler/frontends/prometeu-frontend-pbs/
|
||||||
src/main/resources/
|
src/main/resources/
|
||||||
stdlib/
|
<target>/
|
||||||
1/
|
stdlib/
|
||||||
sdk/
|
1/
|
||||||
composer/
|
core/
|
||||||
main.pbs
|
color/
|
||||||
mod.barrel
|
main.pbs
|
||||||
gfx/
|
mod.barrel
|
||||||
main.pbs
|
sdk/
|
||||||
mod.barrel
|
asset/
|
||||||
asset/
|
main.pbs
|
||||||
main.pbs
|
mod.barrel
|
||||||
mod.barrel
|
composer/
|
||||||
audio/
|
main.pbs
|
||||||
main.pbs
|
mod.barrel
|
||||||
mod.barrel
|
gfx/
|
||||||
core/
|
main.pbs
|
||||||
math/
|
mod.barrel
|
||||||
main.pbs
|
input/
|
||||||
mod.barrel
|
main.pbs
|
||||||
|
mod.barrel
|
||||||
|
log/
|
||||||
|
main.pbs
|
||||||
|
mod.barrel
|
||||||
```
|
```
|
||||||
|
|
||||||
Interpretation:
|
Interpretation:
|
||||||
|
|
||||||
- `stdlib/1` selects stdlib major line `1`,
|
- `<target>` is the `AppMode` export name (`game` for the current line-1 environment),
|
||||||
|
- `game/stdlib/1` selects stdlib major line `1` for that target,
|
||||||
- `sdk` and `core` are reserved project spaces,
|
- `sdk` and `core` are reserved project spaces,
|
||||||
- `composer`, `gfx`, `audio`, `math` are module paths within those reserved spaces,
|
- current line `1` modules are `color`, `asset`, `composer`, `gfx`, `input`, and `log`,
|
||||||
- `main.pbs` and `mod.barrel` form the interface module contents.
|
- `main.pbs` and `mod.barrel` form the interface module contents.
|
||||||
|
|
||||||
|
Current line `1` MUST NOT be documented as shipping `audio` or `@core:math`.
|
||||||
|
Those names are not packaged in the current environment. `@sdk:input` is a
|
||||||
|
VM-owned builtin shell; its path does not make it host-backed.
|
||||||
|
|
||||||
## 5. Logical Mapping
|
## 5. Logical Mapping
|
||||||
|
|
||||||
The compiler must treat the physical layout as a logical stdlib environment.
|
The compiler must treat the physical layout as a logical stdlib environment.
|
||||||
|
|
||||||
Required mapping:
|
Required mapping:
|
||||||
|
|
||||||
- `stdlib/<N>/sdk/gfx` -> `@sdk:gfx`
|
- `<target>/stdlib/<N>/<space>/<module>` -> `@<space>:<module>`
|
||||||
- `stdlib/<N>/sdk/composer` -> `@sdk:composer`
|
|
||||||
- `stdlib/<N>/sdk/asset` -> `@sdk:asset`
|
Current line `1` (`game`) mapping:
|
||||||
- `stdlib/<N>/sdk/audio` -> `@sdk:audio`
|
|
||||||
- `stdlib/<N>/core/math` -> `@core:math`
|
- `game/stdlib/1/core/color` -> `@core:color`
|
||||||
- `stdlib/<N>/core/math/vector` -> `@core:math/vector`
|
- `game/stdlib/1/sdk/asset` -> `@sdk:asset`
|
||||||
|
- `game/stdlib/1/sdk/composer` -> `@sdk:composer`
|
||||||
|
- `game/stdlib/1/sdk/gfx` -> `@sdk:gfx`
|
||||||
|
- `game/stdlib/1/sdk/input` -> `@sdk:input`
|
||||||
|
- `game/stdlib/1/sdk/log` -> `@sdk:log`
|
||||||
|
|
||||||
Rules:
|
Rules:
|
||||||
|
|
||||||
- physical storage is an implementation detail,
|
- physical storage is an implementation detail,
|
||||||
- logical module identity is authoritative,
|
- logical module identity is authoritative,
|
||||||
- callers of the resolver should work with logical addresses such as `@sdk:gfx` and `@sdk:composer`, not resource paths.
|
- callers of the resolver should work with logical addresses such as `@sdk:gfx` and `@core:color`, not resource paths,
|
||||||
|
- physical path MUST NOT imply VM-owned versus host-backed ownership.
|
||||||
|
|
||||||
## 6. Module File Convention
|
## 6. Module File Convention
|
||||||
|
|
||||||
@@ -150,7 +168,8 @@ Minimum operations:
|
|||||||
|
|
||||||
- `resolve(@sdk:gfx)`
|
- `resolve(@sdk:gfx)`
|
||||||
- `resolve(@sdk:composer)`
|
- `resolve(@sdk:composer)`
|
||||||
- `resolve(@core:math/vector)`
|
- `resolve(@sdk:input)`
|
||||||
|
- `resolve(@core:color)`
|
||||||
|
|
||||||
### 7.3 `StdlibModuleSource`
|
### 7.3 `StdlibModuleSource`
|
||||||
|
|
||||||
|
|||||||
@@ -102,17 +102,21 @@ Executable PBS programs have a logical bootstrap sequence before ordinary frame
|
|||||||
Normative order:
|
Normative order:
|
||||||
|
|
||||||
1. materialize globals for each file according to dependency order,
|
1. materialize globals for each file according to dependency order,
|
||||||
2. execute that file's `[Init]`, if present,
|
2. execute that file's non-project `[Init]`, if present,
|
||||||
3. compose those steps into one synthetic module init per module,
|
3. compose those steps into one synthetic module init per module,
|
||||||
4. execute project init, if present,
|
4. execute project init exactly once, if present, after all module initializers,
|
||||||
5. then invoke the userland callable marked with `[Frame]`.
|
5. then invoke the userland callable marked with `[Frame]`.
|
||||||
|
|
||||||
|
The `[Init]` colocated with `[Frame]` is project init. It MUST NOT also run as a file-init fragment.
|
||||||
|
|
||||||
Lifecycle bootstrap is one-shot:
|
Lifecycle bootstrap is one-shot:
|
||||||
|
|
||||||
- no automatic retry occurs after boot failure,
|
- no automatic retry occurs after boot failure,
|
||||||
- failure during module init aborts boot,
|
- failure during module init aborts boot,
|
||||||
- failure during project init aborts boot.
|
- failure during project init aborts boot.
|
||||||
|
|
||||||
|
Common lifecycle assembly materializes this order from the typed declaration. PBS remains the language source of marker meaning; it is not the owner of the published wrapper.
|
||||||
|
|
||||||
## 6.2 Logical frame root and physical wrapper
|
## 6.2 Logical frame root and physical wrapper
|
||||||
|
|
||||||
PBS distinguishes the logical frame root from the physical published entrypoint:
|
PBS distinguishes the logical frame root from the physical published entrypoint:
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# PBS Bytecode and PBX Mapping Specification
|
# Bytecode and PBX Mapping Specification
|
||||||
|
|
||||||
Status: Draft v1 (Backend Baseline)
|
Status: Draft v1 (Backend Baseline)
|
||||||
Applies to: mapping from lowered/optimized backend programs into PBX sections, bytecode-facing artifacts, and source-to-artifact invariants required by loader/verifier/runtime
|
Applies to: mapping from lowered/optimized backend programs into PBX sections, bytecode-facing artifacts, and source-to-artifact invariants required by loader/verifier/runtime
|
||||||
@@ -9,6 +9,10 @@ This document defines the normative mapping between backend-lowered semantics an
|
|||||||
|
|
||||||
Its purpose is to keep artifact emission deterministic and compatible with runtime loader/verifier contracts.
|
Its purpose is to keep artifact emission deterministic and compatible with runtime loader/verifier contracts.
|
||||||
|
|
||||||
|
PBX is the only executable boundary between the compiler and runtime. `IRVM`
|
||||||
|
is a compiler-internal representation consumed by bytecode emission; it MUST
|
||||||
|
NOT be exposed to or consumed by the runtime loader, verifier, or PVM.
|
||||||
|
|
||||||
## 2. Scope
|
## 2. Scope
|
||||||
|
|
||||||
This document defines:
|
This document defines:
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ Applies to: normative stdlib-facing API surface, reserved stdlib project spaces,
|
|||||||
|
|
||||||
This document will define the normative user-facing standard-library surface for PBS.
|
This document will define the normative user-facing standard-library surface for PBS.
|
||||||
|
|
||||||
|
This document is PBS delivery. It does not own console ABI. Intrinsic
|
||||||
|
`final_id` values and host syscall metadata are runtime-owned.
|
||||||
|
|
||||||
## 2. Scope
|
## 2. Scope
|
||||||
|
|
||||||
This document is intended to define:
|
This document is intended to define:
|
||||||
@@ -28,15 +31,22 @@ This document does not define:
|
|||||||
|
|
||||||
Normative precedence:
|
Normative precedence:
|
||||||
|
|
||||||
1. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
|
1. Runtime intrinsic catalog (`../runtime/docs/vm-arch/INTRINSICS.csv`; Studio mirror `docs/vm-arch/INTRINSICS.csv`)
|
||||||
2. `8. Stdlib Environment Packaging and Loading Specification.md`
|
2. Runtime host ABI (`../runtime/docs/specs/runtime/16-host-abi-and-syscalls.md` and `SyscallMeta`)
|
||||||
3. `6. VM-owned vs Host-backed.md`
|
3. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
|
||||||
4. `6.1. Intrinsics and Builtin Types Specification.md`
|
4. `8. Stdlib Environment Packaging and Loading Specification.md`
|
||||||
5. `6.2. Host ABI Binding and Loader Resolution Specification.md`
|
5. `6. VM-owned vs Host-backed.md`
|
||||||
6. This document
|
6. `6.1. Intrinsics and Builtin Types Specification.md`
|
||||||
|
7. `6.2. Host ABI Binding and Loader Resolution Specification.md`
|
||||||
|
8. This document
|
||||||
|
|
||||||
If a rule here conflicts with higher-precedence specs, it is invalid.
|
If a rule here conflicts with higher-precedence specs, it is invalid.
|
||||||
|
|
||||||
|
This document MUST NOT define numeric syscall identifiers, intrinsic `final_id`
|
||||||
|
values, or `SyscallMeta`. PBS `[Host]` and `[IntrinsicCall]` attributes MUST
|
||||||
|
repeat identities already published by those runtime catalogs. They MUST NOT
|
||||||
|
invent console ABI.
|
||||||
|
|
||||||
## 4. Normative Inputs
|
## 4. Normative Inputs
|
||||||
|
|
||||||
This document depends on, at minimum:
|
This document depends on, at minimum:
|
||||||
@@ -57,6 +67,9 @@ The following inputs are already fixed elsewhere and must not be contradicted he
|
|||||||
- User code must import stdlib modules explicitly.
|
- User code must import stdlib modules explicitly.
|
||||||
- Canonical host identity comes from reserved host-binding metadata, not from source owner spelling.
|
- Canonical host identity comes from reserved host-binding metadata, not from source owner spelling.
|
||||||
- VM-owned builtin type, builtin constant, and intrinsic surfaces may be exposed through reserved stdlib shells without transferring semantic ownership away from the VM.
|
- VM-owned builtin type, builtin constant, and intrinsic surfaces may be exposed through reserved stdlib shells without transferring semantic ownership away from the VM.
|
||||||
|
- Console ABI authority is runtime-owned. PBS stdlib is delivery.
|
||||||
|
- Reserved project-space path (`@sdk:*` / `@core:*`) MUST NOT imply VM-owned versus host-backed ownership.
|
||||||
|
- Current stdlib line `1` ships a VM-owned builtin input shell at `@sdk:input`. That exception does not make `@sdk:*` the VM-owned space.
|
||||||
|
|
||||||
## 6. Initial Section Targets
|
## 6. Initial Section Targets
|
||||||
|
|
||||||
@@ -78,7 +91,10 @@ The following items remain to be closed in future agenda discussion.
|
|||||||
- Whether `@core:*` is specified as language-adjacent utility surface or as ordinary stdlib contract.
|
- Whether `@core:*` is specified as language-adjacent utility surface or as ordinary stdlib contract.
|
||||||
- How stdlib API evolution is documented and conformance-tested.
|
- How stdlib API evolution is documented and conformance-tested.
|
||||||
- Whether some interface modules remain toolchain-private and outside user-facing stdlib surface.
|
- Whether some interface modules remain toolchain-private and outside user-facing stdlib surface.
|
||||||
- Whether builtin shells may appear in `@sdk:*` as well as `@core:*`, or whether `@sdk:*` should remain host-facing only by policy.
|
|
||||||
|
Settled by DEC-0048 and not reopened here:
|
||||||
|
|
||||||
|
- Builtin shells MAY appear in `@sdk:*` as well as `@core:*`. Path MUST NOT imply ownership. Current line `1` exception: `@sdk:input`.
|
||||||
|
|
||||||
## 8. Non-Goals
|
## 8. Non-Goals
|
||||||
|
|
||||||
@@ -127,6 +143,12 @@ Rules:
|
|||||||
- but ownership remains governed by the VM-owned vs host-backed classification,
|
- but ownership remains governed by the VM-owned vs host-backed classification,
|
||||||
- and placing a builtin shell in stdlib does not make it host-backed.
|
- and placing a builtin shell in stdlib does not make it host-backed.
|
||||||
|
|
||||||
|
Current line `1` exception:
|
||||||
|
|
||||||
|
- `@sdk:input` exposes VM-owned builtin input types through `[BuiltinType]` and `[IntrinsicCall]`.
|
||||||
|
- that module is not host-backed.
|
||||||
|
- the `@sdk:*` preference for host-backed APIs still holds for new host modules.
|
||||||
|
|
||||||
## 11. Builtin Shell Surfaces
|
## 11. Builtin Shell Surfaces
|
||||||
|
|
||||||
Reserved stdlib modules may expose builtin declarations as compile-time-only
|
Reserved stdlib modules may expose builtin declarations as compile-time-only
|
||||||
@@ -205,6 +227,10 @@ Their canonical runtime-facing identities still come from builtin metadata such
|
|||||||
as `BuiltinType(name="vec2", version=1)` and
|
as `BuiltinType(name="vec2", version=1)` and
|
||||||
`BuiltinConst(target="vec2", name="zero", version=1)`.
|
`BuiltinConst(target="vec2", name="zero", version=1)`.
|
||||||
|
|
||||||
|
Current stdlib line `1` ships `Color` at `@core:color`. The `@core:math` import
|
||||||
|
above is an identity illustration, not a claim that `@core:math` is packaged in
|
||||||
|
line `1`.
|
||||||
|
|
||||||
## 14. Deterministic Stdlib Surface Failures
|
## 14. Deterministic Stdlib Surface Failures
|
||||||
|
|
||||||
At minimum, a conforming implementation must reject:
|
At minimum, a conforming implementation must reject:
|
||||||
@@ -214,3 +240,15 @@ At minimum, a conforming implementation must reject:
|
|||||||
3. a user-facing stdlib module that exports executable PBS bodies for builtin semantics,
|
3. a user-facing stdlib module that exports executable PBS bodies for builtin semantics,
|
||||||
4. a stdlib line that exposes conflicting canonical builtin identities through the same resolved environment,
|
4. a stdlib line that exposes conflicting canonical builtin identities through the same resolved environment,
|
||||||
5. a stdlib line that exposes conflicting canonical host identities through the same resolved environment.
|
5. a stdlib line that exposes conflicting canonical host identities through the same resolved environment.
|
||||||
|
|
||||||
|
## 15. Console ABI Non-Ownership
|
||||||
|
|
||||||
|
This specification MUST NOT:
|
||||||
|
|
||||||
|
1. define numeric syscall identifiers,
|
||||||
|
2. define intrinsic `final_id` values,
|
||||||
|
3. publish `SyscallMeta`,
|
||||||
|
4. or treat PBS `[Host]` / `[IntrinsicCall]` attributes as the ABI catalog.
|
||||||
|
|
||||||
|
PBS shells MUST repeat identities already published by the runtime catalogs
|
||||||
|
named in section 3.
|
||||||
|
|||||||
@@ -1,18 +1,21 @@
|
|||||||
# PBS Verification and Safety Checks Specification
|
# Compiler Verification and Safety Checks Specification
|
||||||
|
|
||||||
Status: Draft v1 (Quality-Gate Baseline)
|
Status: Draft v1 (Quality-Gate Baseline)
|
||||||
Applies to: test-backed safety gates for backend compiler stages and integration regression safety checks against runtime
|
Applies to: test-backed safety gates for common compiler stages, validation ownership across executable frontends, and integration regression safety checks against runtime
|
||||||
|
|
||||||
## 1. Purpose
|
## 1. Purpose
|
||||||
|
|
||||||
This document defines the minimum safety/verification quality gates that must be enforced for executable backend pipelines.
|
This document defines the minimum safety/verification quality gates that must be enforced for executable compiler pipelines, and the ownership rule that separates language validation from platform validation.
|
||||||
|
|
||||||
Its purpose is to keep safety measurable and deterministic across:
|
Its purpose is to keep safety measurable and deterministic across:
|
||||||
|
|
||||||
- lowering,
|
- lowering,
|
||||||
- optimization,
|
- optimization,
|
||||||
- emission,
|
- emission,
|
||||||
- and runtime integration boundaries.
|
- runtime integration boundaries,
|
||||||
|
- and the classification of diagnostics that every executable frontend must obey.
|
||||||
|
|
||||||
|
PBS is the current executable frontend. It is an example, not the owner of this specification.
|
||||||
|
|
||||||
## 2. Scope
|
## 2. Scope
|
||||||
|
|
||||||
@@ -20,37 +23,41 @@ This document defines:
|
|||||||
|
|
||||||
- mandatory compiler-stage safety checks for executable pipeline stages,
|
- mandatory compiler-stage safety checks for executable pipeline stages,
|
||||||
- conditional integration safety regression checks against runtime line,
|
- conditional integration safety regression checks against runtime line,
|
||||||
- and evidence requirements for safety-related support claims.
|
- evidence requirements for safety-related support claims,
|
||||||
|
- and validation-ownership rules that apply to all executable frontends.
|
||||||
|
|
||||||
This document does not define:
|
This document does not define:
|
||||||
|
|
||||||
- full runtime verifier algorithm internals,
|
- full runtime verifier algorithm internals,
|
||||||
- formal proof of all runtime safety properties,
|
- formal proof of all runtime safety properties,
|
||||||
- or one mandatory verifier/optimizer architecture.
|
- one mandatory verifier/optimizer architecture,
|
||||||
|
- PBS syntax or static-semantics catalogs,
|
||||||
|
- or a generic validator-core package.
|
||||||
|
|
||||||
## 3. Authority and Precedence
|
## 3. Authority and Precedence
|
||||||
|
|
||||||
Normative precedence:
|
Normative precedence:
|
||||||
|
|
||||||
1. `docs/pbs/specs/2. Governance and Versioning.md`
|
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
|
||||||
2. `docs/pbs/specs/12. Diagnostics Specification.md`
|
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
|
||||||
3. `20. IRBackend to IRVM Lowering Specification.md`
|
3. `20. IRBackend to IRVM Lowering Specification.md`
|
||||||
4. `21. IRVM Optimization Pipeline Specification.md`
|
4. `21. IRVM Optimization Pipeline Specification.md`
|
||||||
5. `15. Bytecode and PBX Mapping Specification.md`
|
5. `15. Bytecode and PBX Mapping Specification.md`
|
||||||
6. `13. Conformance Test Specification.md`
|
6. `13. Conformance Test Specification.md`
|
||||||
7. This document
|
7. This document
|
||||||
|
8. Frontend diagnostics specifications, including `docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md`, for language-owned coverage only
|
||||||
|
|
||||||
If a rule here conflicts with higher-precedence authorities, it is invalid.
|
If a rule here conflicts with a higher-precedence authority, it is invalid. Frontend diagnostics documents MUST NOT redefine compiler-general safety gates or platform validation ownership.
|
||||||
|
|
||||||
## 4. Normative Inputs
|
## 4. Normative Inputs
|
||||||
|
|
||||||
This document depends on:
|
This document depends on:
|
||||||
|
|
||||||
- `docs/pbs/specs/12. Diagnostics Specification.md`
|
|
||||||
- `13. Conformance Test Specification.md`
|
- `13. Conformance Test Specification.md`
|
||||||
- `15. Bytecode and PBX Mapping Specification.md`
|
- `15. Bytecode and PBX Mapping Specification.md`
|
||||||
- `20. IRBackend to IRVM Lowering Specification.md`
|
- `20. IRBackend to IRVM Lowering Specification.md`
|
||||||
- `21. IRVM Optimization Pipeline Specification.md`
|
- `21. IRVM Optimization Pipeline Specification.md`
|
||||||
|
- `docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md` as the current frontend diagnostics catalog, not as the owner of this specification
|
||||||
|
|
||||||
## 5. Safety Gate Model
|
## 5. Safety Gate Model
|
||||||
|
|
||||||
@@ -133,3 +140,74 @@ This document is healthy when:
|
|||||||
2. executable backends have explicit S-I status (`pass`/`fail`/`deferred`),
|
2. executable backends have explicit S-I status (`pass`/`fail`/`deferred`),
|
||||||
3. integration safety regressions are preserved in tests,
|
3. integration safety regressions are preserved in tests,
|
||||||
4. and safety-related support claims remain evidence-backed.
|
4. and safety-related support claims remain evidence-backed.
|
||||||
|
|
||||||
|
## 11. Validation Ownership
|
||||||
|
|
||||||
|
A validation MUST live at the lowest layer that understands the failure without knowing the source language.
|
||||||
|
|
||||||
|
- A check is language-owned if it needs AST, tokens, a language marker, a barrel, or another source-language rule.
|
||||||
|
- A check is platform-owned if it can be performed on `IRBackend`, `IRLifecycleDeclaration`, IRVM, PBX, host/capability tables, or ids.
|
||||||
|
|
||||||
|
Adding a validation MUST record:
|
||||||
|
|
||||||
|
1. the input artifact the check reads;
|
||||||
|
2. whether that artifact is language source/AST/marker or a common contract;
|
||||||
|
3. the matrix owner;
|
||||||
|
4. the code family (`E_PARSE_*` / `E_SEM_*` / `E_LINK_*` / `E_HOST_*` versus `COMMON_*` / `LOWER_IRVM_*` / `MARSHAL_*`);
|
||||||
|
5. whether the span comes from a common-contract origin or from language tokens/AST.
|
||||||
|
|
||||||
|
If item 2 is both, the implementation MUST emit two diagnostics with distinct identities, not one hybrid.
|
||||||
|
|
||||||
|
### 11.1 Diagnostic identity and span
|
||||||
|
|
||||||
|
Platform diagnostics MUST use `COMMON_*`, `LOWER_IRVM_*`, or `MARSHAL_*` codes and the phase of the pipeline stage that reports them.
|
||||||
|
|
||||||
|
PBS MUST keep its current `E_PARSE_*`, `E_SEM_*`, `E_LINK_*`, and `E_HOST_*` codes.
|
||||||
|
|
||||||
|
This specification MUST NOT rewrite diagnostic messages or renumber existing codes.
|
||||||
|
|
||||||
|
Common code MUST copy origin/span when the declaration, instruction, or metadata carries one. A missing origin MUST be a structural error. Implementations MUST NOT invent a span.
|
||||||
|
|
||||||
|
The same fact MAY exist on both sides. PBS explains the language rule; the common layer rejects an invalid handoff even when the frontend has no PBS markers. The two errors MUST keep distinct identities. Example: `E_SEM_MISSING_PROJECT_FRAME` and a missing frame root on an executable `IRLifecycleDeclaration`.
|
||||||
|
|
||||||
|
### 11.2 Initial ownership matrix
|
||||||
|
|
||||||
|
| Family | Owner | Status | Notes |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Parse / syntax (`ParseErrors`) | `compiler/pbs` | language | remains |
|
||||||
|
| Type, flow, declaration, const, and source-form global semantics | `compiler/pbs` | language | remains |
|
||||||
|
| Markers `[Init]`, `[Frame]`, `InitAllowed`, signature, colocation | `compiler/pbs` | language | already split by lifecycle assembly |
|
||||||
|
| `host call not allowed during init` | `compiler/pbs` | language | marker/source rule |
|
||||||
|
| PBS linking (`PbsLinkErrors`, barrel, import, visibility) | `compiler/pbs` | language | do not extract |
|
||||||
|
| Source shape of `[Host]` / `[Capability]` | `compiler/pbs` | language | host-admission split |
|
||||||
|
| Canonical host-binding identity and capability over `IRReservedMetadata` | `compiler/general` | platform | classified; validator remains in the PBS package until a later plan |
|
||||||
|
| Lifecycle assembler | `compiler/general` | platform | already implemented |
|
||||||
|
| IRVM preconditions for wrapper, boot guard, origin | `compiler/general` | platform | already implemented |
|
||||||
|
| `IRVMValidator`, lowering, marshal/bytecode | `compiler/general` | platform | already implemented |
|
||||||
|
| `Addressable` / asset path | `compiler/general` | platform | classified; no extra migration in this specification |
|
||||||
|
| Gates S-U/S-I | `compiler/general` | platform | this document |
|
||||||
|
|
||||||
|
### 11.3 Host admission, assets, and linking
|
||||||
|
|
||||||
|
Host admission is split:
|
||||||
|
|
||||||
|
- language owns the source shape of `[Host]` and `[Capability]`;
|
||||||
|
- platform owns canonical binding identity `(module, name, version)`, unknown capability, undeclared capability, and inconsistent binding once those facts exist on `IRReservedMetadata`.
|
||||||
|
|
||||||
|
`PbsHostAdmissionValidator` MAY remain in the PBS package until a later plan. `E_HOST_*` MUST NOT be treated as eternal PBS semantics.
|
||||||
|
|
||||||
|
`Addressable` / asset-path resolution is platform-owned. This specification classifies it and MUST NOT move additional asset code.
|
||||||
|
|
||||||
|
PBS linking, barrel files, and `PbsLinkErrors` remain language-owned. `ResolveDeps` does not authorize extracting them.
|
||||||
|
|
||||||
|
### 11.4 What this section does not authorize
|
||||||
|
|
||||||
|
This specification MUST NOT be read as authorizing:
|
||||||
|
|
||||||
|
- a generic validator-core package;
|
||||||
|
- moving `PbsHostAdmissionValidator` into a common package;
|
||||||
|
- moving asset-resolution production code;
|
||||||
|
- extracting PBS linking;
|
||||||
|
- or reopening lifecycle-assembly ownership.
|
||||||
|
|
||||||
|
Platform validators MUST NOT depend on types from the PBS frontend module (`prometeu-frontend-pbs`). The package `p.studio.compiler.pbs` is not the complete boundary; facades shipped by that module remain PBS-owned. Platform validators MUST NOT discover roles from `__pbs.` prefixes.
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# PBS IRBackend to IRVM Lowering Specification
|
# IRBackend to IRVM Lowering Specification
|
||||||
|
|
||||||
Status: Draft v1 (Backend Baseline)
|
Status: Draft v1 (Backend Baseline)
|
||||||
Applies to: executable-backend lowering from `IRBackend` handoff into `IRVM`
|
Applies to: executable-backend lowering from the common `IRBackend` handoff into `IRVM`
|
||||||
|
|
||||||
## 1. Purpose
|
## 1. Purpose
|
||||||
|
|
||||||
@@ -9,11 +9,20 @@ This document defines the normative lowering contract from executable `IRBackend
|
|||||||
|
|
||||||
Its purpose is to make backend lowering deterministic, reviewable, and compatible with runtime ISA/verification authority.
|
Its purpose is to make backend lowering deterministic, reviewable, and compatible with runtime ISA/verification authority.
|
||||||
|
|
||||||
|
`IRBackend` is the common frontend-to-backend executable handoff. It is emitted by frontends and consumed by common backend stages. Backend lowering MUST NOT require PBS AST nodes, PBS tokens, PBS parser structures, PBS semantic objects, PBS editorial objects, or equivalent language-owned objects from future frontends.
|
||||||
|
|
||||||
|
`IRVM` is an internal compiler representation. It MUST be consumed by common
|
||||||
|
compiler optimization and PBX emission stages, and it MUST NOT cross the
|
||||||
|
compiler/runtime boundary or become an input, dependency, public type, or
|
||||||
|
operational concept of the runtime loader, verifier, or PVM. PBX is the only
|
||||||
|
executable artifact boundary between compiler and runtime.
|
||||||
|
|
||||||
## 2. Scope
|
## 2. Scope
|
||||||
|
|
||||||
This document defines:
|
This document defines:
|
||||||
|
|
||||||
- required backend preconditions before `IRBackend -> IRVM` starts,
|
- required backend preconditions before `IRBackend -> IRVM` starts,
|
||||||
|
- allowed language-neutral `IRBackend` contract concepts at the backend boundary,
|
||||||
- `IRVM` structural obligations needed before optimization/emission,
|
- `IRVM` structural obligations needed before optimization/emission,
|
||||||
- deterministic function-id assignment and control-flow lowering obligations,
|
- deterministic function-id assignment and control-flow lowering obligations,
|
||||||
- callsite lowering obligations across function, host-backed, and VM-owned intrinsic paths,
|
- callsite lowering obligations across function, host-backed, and VM-owned intrinsic paths,
|
||||||
@@ -25,7 +34,8 @@ This document does not define:
|
|||||||
- binary PBX layout details,
|
- binary PBX layout details,
|
||||||
- loader patching internals,
|
- loader patching internals,
|
||||||
- runtime execution internals,
|
- runtime execution internals,
|
||||||
- or one mandatory optimizer implementation.
|
- one mandatory optimizer implementation,
|
||||||
|
- or frontend-specific lowering rules before `IRBackend` emission.
|
||||||
|
|
||||||
## 3. Authority and Precedence
|
## 3. Authority and Precedence
|
||||||
|
|
||||||
@@ -33,8 +43,8 @@ Normative precedence:
|
|||||||
|
|
||||||
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
|
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
|
||||||
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
|
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
|
||||||
3. `docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md`
|
3. This document
|
||||||
4. This document
|
4. Frontend-specific lowering specifications, including `docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md`
|
||||||
|
|
||||||
If a rule here conflicts with higher-precedence authorities, it is invalid.
|
If a rule here conflicts with higher-precedence authorities, it is invalid.
|
||||||
|
|
||||||
@@ -42,22 +52,106 @@ If a rule here conflicts with higher-precedence authorities, it is invalid.
|
|||||||
|
|
||||||
This document depends on:
|
This document depends on:
|
||||||
|
|
||||||
- `docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md`
|
|
||||||
- `docs/specs/compiler-languages/pbs/6.1. Intrinsics and Builtin Types Specification.md`
|
- `docs/specs/compiler-languages/pbs/6.1. Intrinsics and Builtin Types Specification.md`
|
||||||
- `docs/specs/compiler-languages/pbs/6.2. Host ABI Binding and Loader Resolution Specification.md`
|
- `docs/specs/compiler-languages/pbs/6.2. Host ABI Binding and Loader Resolution Specification.md`
|
||||||
|
- frontend-specific lowering specifications that emit the common `IRBackend` handoff
|
||||||
- `15. Bytecode and PBX Mapping Specification.md`
|
- `15. Bytecode and PBX Mapping Specification.md`
|
||||||
- `21. IRVM Optimization Pipeline Specification.md`
|
- `21. IRVM Optimization Pipeline Specification.md`
|
||||||
|
|
||||||
|
## 4.1 Common IRBackend Contract
|
||||||
|
|
||||||
|
At this boundary, `IRBackend` may contain only language-neutral compiler concepts required by executable backend lowering:
|
||||||
|
|
||||||
|
1. source identity and spans,
|
||||||
|
2. modules and module identifiers,
|
||||||
|
3. callable identities, signatures, names, arity, and type-shape surfaces,
|
||||||
|
4. executable functions,
|
||||||
|
5. instruction kinds and instruction metadata,
|
||||||
|
6. globals and global origins,
|
||||||
|
7. synthetic executable functions and synthetic origins,
|
||||||
|
8. host-call metadata,
|
||||||
|
9. intrinsic metadata,
|
||||||
|
10. reserved metadata required for backend lowering,
|
||||||
|
11. required runtime or platform capabilities,
|
||||||
|
12. and an optional typed `IRLifecycleDeclaration` used as lifecycle provenance after common assembly.
|
||||||
|
|
||||||
|
The common backend contract MUST express these concepts as backend obligations, not as PBS syntax or PBS semantic rules. When a concept currently originates from PBS, the backend contract still owns only the language-neutral obligation carried by `IRBackend`.
|
||||||
|
|
||||||
|
### 4.3 IRLifecycleDeclaration
|
||||||
|
|
||||||
|
`IRLifecycleDeclaration` is the typed, immutable, serializable-by-design lifecycle provenance carried by `IRBackend`.
|
||||||
|
|
||||||
|
An executable handoff MUST contain exactly one declaration before common assembly. A deliberately non-executable handoff MAY omit it; absence MUST NOT synthesize a default `main` or published wrapper.
|
||||||
|
|
||||||
|
The declaration MUST represent, using ordered collections and typed ids:
|
||||||
|
|
||||||
|
1. modules in explicit dependency order,
|
||||||
|
2. each module's ordered file-init fragment references,
|
||||||
|
3. an optional project-init callable reference,
|
||||||
|
4. and exactly one frame-root callable reference.
|
||||||
|
|
||||||
|
References MUST use `ModuleId`, `FileId`, `CallableId`, a typed role, and source attribution. The public shape MUST NOT expose maps, sets, callbacks, compiler services, or frontend-owned types.
|
||||||
|
|
||||||
|
`AssembleLifecyclePipelineStage` MUST run after `FrontendPhasePipelineStage` and before `LowerToIRVMPipelineStage`. `LifecycleAssemblerService` is the only owner of derived lifecycle artifacts: module init, project-init wrapper, published frame wrapper, physical entrypoint, and hidden boot guard. Those artifacts MUST use deterministic neutral internal identities. Common code MUST NOT discover roles from `__pbs.*` prefixes or depend on types from the PBS frontend module (`prometeu-frontend-pbs`). The package `p.studio.compiler.pbs` is not the complete boundary.
|
||||||
|
|
||||||
|
The declaration MUST remain available on the assembled `IRBackend` as typed provenance. Downstream inspection MUST use roles, ids, and origins rather than synthetic names.
|
||||||
|
|
||||||
|
Project init MUST be absent from file-init fragments and MUST execute exactly once, after all module initializers and before the frame root. Bootstrap failure MUST abort without retry. The boot guard MUST prevent a second bootstrap after successful completion. The published wrapper owns the final frame return.
|
||||||
|
|
||||||
|
The common backend contract MUST NOT expose or require:
|
||||||
|
|
||||||
|
1. `PbsExpression`, `PbsStatement`, `PbsToken`, or equivalent PBS-owned syntax objects,
|
||||||
|
2. PBS parser cursors, parse contexts, parse nodes, or token kinds,
|
||||||
|
3. PBS semantic validator internals,
|
||||||
|
4. PBS editorial or language-service objects,
|
||||||
|
5. or any type from the PBS frontend module (`prometeu-frontend-pbs`) or an equivalent language frontend module as part of the public backend handoff.
|
||||||
|
|
||||||
|
## 4.2 Serializable-by-Design Contract Shape
|
||||||
|
|
||||||
|
The public `IRBackend` handoff MUST remain serializable by design. This requirement does not select a wire format, schema language, RPC mechanism, process boundary, plugin runtime, or external frontend transport. It only constrains the public data shape so those choices remain possible later without redesigning the handoff.
|
||||||
|
|
||||||
|
Public `IRBackend` contract types MUST be modelable as an acyclic, deterministic data graph made of:
|
||||||
|
|
||||||
|
1. primitive values and strings,
|
||||||
|
2. enums,
|
||||||
|
3. immutable value objects,
|
||||||
|
4. ordered lists,
|
||||||
|
5. nullable or optional scalar fields only where absence is part of the contract,
|
||||||
|
6. explicit identifier values for cross-references,
|
||||||
|
7. and source attribution values such as file ids and spans.
|
||||||
|
|
||||||
|
The public handoff MUST NOT expose, require, or rely on:
|
||||||
|
|
||||||
|
1. callbacks, lambdas, service objects, registries, visitors, or live compiler services,
|
||||||
|
2. frontend AST, parser, token, semantic, or editorial objects,
|
||||||
|
3. mutable global state as part of interpretation,
|
||||||
|
4. object identity equality as a semantic key,
|
||||||
|
5. unordered collections where iteration order affects output,
|
||||||
|
6. cyclic references between public handoff objects,
|
||||||
|
7. lazy values whose result depends on current process state,
|
||||||
|
8. or a selected wire format.
|
||||||
|
|
||||||
|
Cross-object references MUST use explicit ids or stable symbolic keys. Existing table-scoped identifiers such as `FileId`, `ModuleId`, `CallableId`, and `IntrinsicId` are valid handoff values when their table scope is explicit and deterministic. New typed ids SHOULD be introduced only when a concrete public handoff field would otherwise depend on textual identity, object identity, or a direct object reference.
|
||||||
|
|
||||||
|
Ordered collections MUST preserve deterministic order. Any map-like data that becomes part of the handoff MUST either be represented as an ordered list of entries or define deterministic key ordering before it reaches the public contract.
|
||||||
|
|
||||||
|
Initial enforcement for this contract SHOULD be audit and guardrail based: specs, reflection tests over public handoff surfaces, deterministic ordering tests, and targeted fixes for concrete leaks. A serializer or schema implementation is not required for conformance to this subsection.
|
||||||
|
|
||||||
## 5. Backend Entry Preconditions
|
## 5. Backend Entry Preconditions
|
||||||
|
|
||||||
Lowering from `IRBackend` to `IRVM` may start only when:
|
Lowering from `IRBackend` to `IRVM` may start only when:
|
||||||
|
|
||||||
1. frontend admission to `IRBackend` is complete for the active slice,
|
1. frontend admission to `IRBackend` is complete for the active slice,
|
||||||
2. required callsite categories (`CALL_FUNC`/`CALL_HOST`/`CALL_INTRINSIC`) are available,
|
2. common lifecycle assembly has already materialized derived artifacts for an executable handoff,
|
||||||
3. required canonical host/intrinsic metadata is available for admitted callsites,
|
3. required callsite categories (`CALL_FUNC`/`CALL_HOST`/`CALL_INTRINSIC`) are available,
|
||||||
4. dependency-scoped fail-fast exclusions have already been applied at the `IRBackend` boundary,
|
4. required canonical host/intrinsic metadata is available for admitted callsites,
|
||||||
5. compiler-selected published-wrapper entrypoint identity is present and unambiguous,
|
5. dependency-scoped fail-fast exclusions have already been applied at the `IRBackend` boundary,
|
||||||
6. and target `vm_profile` is selected deterministically.
|
6. compiler-selected published-wrapper entrypoint identity is present and unambiguous,
|
||||||
|
7. and target `vm_profile` is selected deterministically.
|
||||||
|
|
||||||
|
Declaration validation, role uniqueness, explicit order, and rejection of frontend-preassembled derived artifacts belong to `LifecycleAssemblerService`. `IRBackend -> IRVM` MUST keep only backend preconditions on the assembled graph, such as published-wrapper identity, synthetic origin presence, and hidden boot-guard presence. It MUST NOT reconstruct lifecycle order from callable names.
|
||||||
|
|
||||||
|
Those common structural diagnostics are compiler-general. Classification, code families, and dual language/platform reporting are owned by `docs/specs/compiler/19. Verification and Safety Checks Specification.md` section 11. They MUST NOT be catalogued as PBS-facing required coverage.
|
||||||
|
|
||||||
## 6. IRVM Model Obligations
|
## 6. IRVM Model Obligations
|
||||||
|
|
||||||
@@ -98,12 +192,15 @@ Function indexing must be deterministic:
|
|||||||
4. manifest-owned or name-only entrypoint fallback is forbidden,
|
4. manifest-owned or name-only entrypoint fallback is forbidden,
|
||||||
5. and identical admitted input graphs must produce identical function-id assignments.
|
5. and identical admitted input graphs must produce identical function-id assignments.
|
||||||
|
|
||||||
For PBS executable lowering:
|
For executable lowering:
|
||||||
|
|
||||||
- the userland callable marked with `[Frame]` remains the logical frame root,
|
- the declared frame-root callable remains the logical frame root,
|
||||||
- the wrapper path must contain final `FRAME_RET`,
|
- the assembled published wrapper is the physical entrypoint,
|
||||||
|
- the wrapper path must contain the final frame return,
|
||||||
- and lowering must preserve that distinction through `IRVM`.
|
- and lowering must preserve that distinction through `IRVM`.
|
||||||
|
|
||||||
|
PBS `[Init]`/`[Frame]` markers are a frontend source of the declaration. The backend-owned obligation is the neutral requirement that the compiler-selected published wrapper be the physical entrypoint and that lifecycle provenance remain explicit in `IRBackend` through typed roles and ids. Neutral synthetic names are internal and are not a public ABI.
|
||||||
|
|
||||||
## 9. Callsite Lowering Obligations
|
## 9. Callsite Lowering Obligations
|
||||||
|
|
||||||
### 9.1 Function calls
|
### 9.1 Function calls
|
||||||
@@ -150,7 +247,7 @@ Before bytecode emission, backend must run structural pre-verification on lowere
|
|||||||
7. and structural validity of host/intrinsic call forms.
|
7. and structural validity of host/intrinsic call forms.
|
||||||
8. and structural validity of backend-owned symbolic-to-operational rewrites such as `Addressable -> asset_id`.
|
8. and structural validity of backend-owned symbolic-to-operational rewrites such as `Addressable -> asset_id`.
|
||||||
|
|
||||||
For PBS host-backed asset calls in v1, this validation includes the rewrite selected by preserved host metadata such as `[AssetLowering(param = N)]`.
|
For host-backed asset calls in v1, this validation includes backend-owned symbolic-to-operational rewrites selected by preserved host metadata. PBS currently emits this designation from metadata such as `[AssetLowering(param = N)]`, but final operational resolution is a common backend obligation.
|
||||||
|
|
||||||
This pre-verification does not replace runtime verifier authority.
|
This pre-verification does not replace runtime verifier authority.
|
||||||
|
|
||||||
@@ -184,4 +281,6 @@ This document is healthy when:
|
|||||||
1. `IRBackend -> IRVM` obligations are explicit and testable,
|
1. `IRBackend -> IRVM` obligations are explicit and testable,
|
||||||
2. deterministic function/call/control-flow lowering rules are explicit,
|
2. deterministic function/call/control-flow lowering rules are explicit,
|
||||||
3. mandatory pre-verification boundary is explicit,
|
3. mandatory pre-verification boundary is explicit,
|
||||||
4. and scope boundaries with optimization/emission specs are explicit.
|
4. common backend obligations are not described as owned by PBS,
|
||||||
|
5. frontend-specific lowering specs only own emission into `IRBackend`,
|
||||||
|
6. and scope boundaries with optimization/emission specs are explicit.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# PBS IRVM Optimization Pipeline Specification
|
# IRVM Optimization Pipeline Specification
|
||||||
|
|
||||||
Status: Draft v1 (Pipeline Baseline)
|
Status: Draft v1 (Pipeline Baseline)
|
||||||
Applies to: placement and invariants of the `OptimizeIRVM` stage between lowering and bytecode emission
|
Applies to: placement and invariants of the `OptimizeIRVM` stage between lowering and bytecode emission
|
||||||
@@ -9,6 +9,10 @@ This document defines the normative placement and safety invariants of the `Opti
|
|||||||
|
|
||||||
Its purpose is to allow optimization in the backend pipeline without transferring semantic optimization responsibility to runtime.
|
Its purpose is to allow optimization in the backend pipeline without transferring semantic optimization responsibility to runtime.
|
||||||
|
|
||||||
|
`IRVM` is internal to the compiler. Optimization output MUST flow to PBX
|
||||||
|
emission and MUST NOT be exposed as a runtime input or protocol. PBX remains the
|
||||||
|
only executable boundary consumed by the runtime loader, verifier, and PVM.
|
||||||
|
|
||||||
## 2. Scope
|
## 2. Scope
|
||||||
|
|
||||||
This document defines:
|
This document defines:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
Status: Draft v1 (Traceability Baseline)
|
Status: Draft v1 (Traceability Baseline)
|
||||||
Applies to: compiler/backend conformance traceability for canonical stage order and entrypoint-specific contracts
|
Applies to: compiler/backend conformance traceability for canonical stage order and entrypoint-specific contracts
|
||||||
|
|
||||||
Last Updated: 2026-03-30
|
Last Updated: 2026-09-19
|
||||||
|
|
||||||
## 1. Purpose
|
## 1. Purpose
|
||||||
|
|
||||||
@@ -13,7 +13,7 @@ This matrix maps each normative backend MUST from:
|
|||||||
2. `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
|
2. `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
|
||||||
3. `docs/specs/compiler/21. IRVM Optimization Pipeline Specification.md`
|
3. `docs/specs/compiler/21. IRVM Optimization Pipeline Specification.md`
|
||||||
4. `docs/specs/compiler/23. Compiler Pipeline Entry Points Specification.md`
|
4. `docs/specs/compiler/23. Compiler Pipeline Entry Points Specification.md`
|
||||||
5. `docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md` (Section 12 addendum only)
|
5. `docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md` (PBS lowering obligations only)
|
||||||
|
|
||||||
to concrete positive/negative test evidence and current status.
|
to concrete positive/negative test evidence and current status.
|
||||||
|
|
||||||
@@ -40,6 +40,22 @@ to concrete positive/negative test evidence and current status.
|
|||||||
| G19-5.2.6 | Gate S-I MUST reject missing capability at load-time. | N/A | `BackendGateIIntegrationTest#gateI_rejectMissingCapability` | pass | |
|
| G19-5.2.6 | Gate S-I MUST reject missing capability at load-time. | N/A | `BackendGateIIntegrationTest#gateI_rejectMissingCapability` | pass | |
|
||||||
| G19-5.2.7 | Gate S-I MUST cover valid VM-owned intrinsic path. | `BackendGateIIntegrationTest#gateI_validIntrinsicPath` | N/A | pass | |
|
| G19-5.2.7 | Gate S-I MUST cover valid VM-owned intrinsic path. | `BackendGateIIntegrationTest#gateI_validIntrinsicPath` | N/A | pass | |
|
||||||
| G19-5.2.8 | Gate S-I MUST cover repeatability across runtime line. | `RuntimeBackedCompatibilityAdapterTest#checkMustPassInStrictModeWhenRuntimeCommandIsValid`; `RuntimeBackedCompatibilityAdapterTest#checkMustBeRepeatableAcrossDeclaredRuntimeLinesInStrictMode` | `RuntimeBackedCompatibilityAdapterTest#checkMustFailInStrictModeWhenRuntimeCommandIsUnavailable` | pass | Multi-line repeatability is asserted with strict runtime-backed checks over distinct declared runtime lines. |
|
| G19-5.2.8 | Gate S-I MUST cover repeatability across runtime line. | `RuntimeBackedCompatibilityAdapterTest#checkMustPassInStrictModeWhenRuntimeCommandIsValid`; `RuntimeBackedCompatibilityAdapterTest#checkMustBeRepeatableAcrossDeclaredRuntimeLinesInStrictMode` | `RuntimeBackedCompatibilityAdapterTest#checkMustFailInStrictModeWhenRuntimeCommandIsUnavailable` | pass | Multi-line repeatability is asserted with strict runtime-backed checks over distinct declared runtime lines. |
|
||||||
|
| G19-11.1 | A validation MUST live at the lowest layer that understands the failure without knowing the source language. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership` | N/A | pass | Spec 19 section 11 states the classification rule. |
|
||||||
|
| G19-11.2 | Spec 19 MUST publish the validation ownership matrix. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership` | N/A | pass | Matrix families include parse/syntax, PBS linking, and lifecycle assembler. |
|
||||||
|
| G19-11.3 | Platform diagnostics MUST use `COMMON_*` / `LOWER_IRVM_*` / `MARSHAL_*` and MUST copy origin/span when present. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership`; `LifecycleAssemblerServiceTest#assembleMustRejectMissingFrameRootWithoutRepair` | N/A | pass | Code families and span policy are normative in spec 19 section 11.1. |
|
||||||
|
| G19-11.4 | The same fact MAY exist as a language diagnostic and a platform diagnostic with distinct identities. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership` | N/A | pass | Dual reporting is required when a check reads both source and common contract. |
|
||||||
|
| G19-11.5 | Host admission MUST split source attribute shape from canonical `IRReservedMetadata` identity without moving the PBS validator in this plan. | `ValidationOwnershipSpecTest#spec19MustBeCompilerGeneralAndPublishValidationOwnership` | N/A | pass | Classified as platform; validator remains in the PBS package. |
|
||||||
|
| G19-11.6 | Platform validators MUST NOT depend on PBS frontend module types or match `__pbs.` prefixes. | `PbsModuleBoundaryArchTest#productionOutsideAllowlistMustNotDependOnPbsModuleTypes`; `CommonBackendPbsPrefixScanTest#commonLifecycleAndBackendMustNotDiscoverRolesFromPbsNamePrefixes` | N/A | pass | ArchUnit covers PBS module origin, including facades outside `p.studio.compiler.pbs`; source scan still rejects `__pbs.` in backend, lifecycle, and common pipeline stages. |
|
||||||
|
| PBS12-11 | PBS diagnostics MUST NOT claim common structural lifecycle/IRVM failures as PBS required coverage. | `ValidationOwnershipSpecTest#pbsDiagnosticsMustNotClaimCommonStructuralFailures` | N/A | pass | PBS spec 12 points those failures at spec 19 section 11 and spec 20. |
|
||||||
|
| G20-4.1.1 | `IRBackend` MUST be the common frontend-to-backend executable handoff. | `LowerToIRVMServiceTest#lowerMustAcceptManuallyConstructedCommonIRBackend` | N/A | pass | Direct backend lowering from manually constructed common IRBackend proves PBS parser/frontend services are not required. |
|
||||||
|
| G20-4.1.2 | Common backend code MUST NOT depend on types from the PBS frontend module. | `PbsModuleBoundaryArchTest#productionOutsideAllowlistMustNotDependOnPbsModuleTypes`; `PbsModuleBoundaryArchTest#irBackendModelsMustNotDependOnPbsModuleTypes` | N/A | pass | ArchUnit rejects PBS-module origin types in common production code, including facades outside `p.studio.compiler.pbs`. |
|
||||||
|
| G20-4.1.3 | Public `IRBackend` contract MUST NOT expose PBS AST, token, parser, semantic, or editorial types. | `IRBackendExecutableContractTest#publicIRBackendContractMustNotExposePbsTypes` | N/A | pass | Reflection guard covers public contract fields, constructors, methods, and record components. |
|
||||||
|
| G20-4.2.1 | Public `IRBackend` contract types MUST remain modelable as an acyclic, deterministic data graph. | `IRBackendExecutableContractTest#publicIRBackendContractMustExposeOnlySerializableShapes`; `IRBackendExecutableContractTest#aggregatorMustEmitDeterministicOrderedPublicContractShape` | N/A | pass | Covers public shape guardrails, generic type arguments, ordered aggregate emission, table remapping, and capability de-duplication order. |
|
||||||
|
| G20-4.2.2 | Public `IRBackend` contract types MUST NOT expose callbacks, services, mutable/unordered collection contracts, frontend-owned objects, process-dependent lazy values, cyclic public references, or wire-format commitments. | `IRBackendExecutableContractTest#publicIRBackendContractMustExposeOnlySerializableShapes` | N/A | pass | Reflection guard covers public contract fields, constructors, methods, record components, and generic type arguments. |
|
||||||
|
| G20-4.2.3 | Public `IRBackend` cross-object references MUST use explicit ids or stable symbolic keys. | `IRBackendExecutableContractTest#publicIRBackendContractAuditMustClassifyAllowedSupportTypes`; `IRBackendExecutableContractTest#publicIRBackendContractMustUseExplicitIdsOrStableKeysForKnownReferences` | N/A | pass | Current audit found no concrete public serialization leak requiring model correction. Existing `FileId`, `ModuleId`, `CallableId`, and `IntrinsicId` remain explicit table-scoped identifiers. |
|
||||||
|
| G20-4.3.1 | Executable `IRBackend` MUST carry a typed, ordered, id-based `IRLifecycleDeclaration` as provenance. | `IRBackendExecutableContractTest#aggregatorMustRemapTypedLifecycleReferencesAndPreserveDeclaredModuleOrder`; `LifecycleAssemblerServiceTest#assembleMustMaterializeNeutralLifecycleArtifactsInDeclaredOrder` | `IRBackendExecutableContractTest#aggregatorMustOmitLifecycleDeclarationWhenNoFileContributesOne` | pass | Declaration uses `ReadOnlyList`, typed ids, roles, and source attribution; aggregator remaps ids with explicit module order. |
|
||||||
|
| G20-4.3.2 | Missing lifecycle declaration MUST mean a deliberately non-executable handoff and MUST NOT synthesize entrypoints. | `LifecycleAssemblerServiceTest#assembleMustNoOpWhenLifecycleDeclarationIsAbsent`; `AssembleLifecyclePipelineStageTest#runMustNoOpForDeliberatelyNonExecutableHandoff` | N/A | pass | Assembler and stage leave the backend unchanged when the declaration is absent. |
|
||||||
|
| G20-4.3.3 | Common lifecycle assembly MUST be the exclusive owner of derived artifacts and MUST use neutral identities. | `LifecycleAssemblerServiceTest#assembleMustMaterializeNeutralLifecycleArtifactsInDeclaredOrder`; `CommonBackendPbsPrefixScanTest#commonLifecycleAndBackendMustNotDiscoverRolesFromPbsNamePrefixes`; `PbsModuleBoundaryArchTest#productionOutsideAllowlistMustNotDependOnPbsModuleTypes` | `LifecycleAssemblerServiceTest#assembleMustRejectPreMaterializedDerivedArtifacts` | pass | Derived wrappers and boot guard are common-owned; ArchUnit rejects PBS-module types and the source scan rejects `__pbs.` prefix matching. |
|
||||||
| G20-6.2 | `IRVM_EXT` MUST declare structural metadata (`pops/pushes/is_branch/is_terminator`). | `IRVMValidatorTest#validateMustApplyStructuralMetadataForCustomInternalExtension`; `IRVMValidatorTest#validateMustRejectCustomInternalExtensionWhenStructuralMetadataUnderflowsStack`; `IRVMOp` record contract (`pops/pushes/branch/terminator/internal`) | N/A | pass | Dedicated extension fixtures now assert structural metadata is consumed by validation behavior. |
|
| G20-6.2 | `IRVM_EXT` MUST declare structural metadata (`pops/pushes/is_branch/is_terminator`). | `IRVMValidatorTest#validateMustApplyStructuralMetadataForCustomInternalExtension`; `IRVMValidatorTest#validateMustRejectCustomInternalExtensionWhenStructuralMetadataUnderflowsStack`; `IRVMOp` record contract (`pops/pushes/branch/terminator/internal`) | N/A | pass | Dedicated extension fixtures now assert structural metadata is consumed by validation behavior. |
|
||||||
| G20-6.3 | `IRVM_EXT` MUST be eliminable before bytecode emission. | `OptimizeIRVMServiceTest#optimizeDefaultPassesMustEliminateUnreachableInternalExtensionBeforeEmission` | `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemain`; `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemainEvenWithNonEmptyEmissionPlan`; `IRVMValidatorTest#validateMustRejectInternalOpcodeWhenConfigured` | pass | Optimizer elimination path and emit-stage hard rejection path are both covered. |
|
| G20-6.3 | `IRVM_EXT` MUST be eliminable before bytecode emission. | `OptimizeIRVMServiceTest#optimizeDefaultPassesMustEliminateUnreachableInternalExtensionBeforeEmission` | `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemain`; `EmitBytecodePipelineStageTest#runMustFailWhenInternalOpcodesRemainEvenWithNonEmptyEmissionPlan`; `IRVMValidatorTest#validateMustRejectInternalOpcodeWhenConfigured` | pass | Optimizer elimination path and emit-stage hard rejection path are both covered. |
|
||||||
| G20-6.4 | IRVM MUST preserve per-function slot and identity headers. | `IRVMProgramTest#constructorMustRejectModuleAndEmissionPlanMismatch` | `IRVMProgramTest#constructorMustRejectModuleAndEmissionPlanMismatch` | pass | Header mismatch is rejected deterministically. |
|
| G20-6.4 | IRVM MUST preserve per-function slot and identity headers. | `IRVMProgramTest#constructorMustRejectModuleAndEmissionPlanMismatch` | `IRVMProgramTest#constructorMustRejectModuleAndEmissionPlanMismatch` | pass | Header mismatch is rejected deterministically. |
|
||||||
@@ -67,14 +83,19 @@ to concrete positive/negative test evidence and current status.
|
|||||||
| G21-9.1 | Validation MUST include optimized-vs-non-optimized equivalence fixtures. | `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForLoweredHostIntrinsicFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForConditionalJoinFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForSimpleLoopFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForLinearCallFixture` | N/A | pass | Dedicated opt on/off harness with reusable interpreter and deterministic trace assertions is in place. |
|
| G21-9.1 | Validation MUST include optimized-vs-non-optimized equivalence fixtures. | `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForLoweredHostIntrinsicFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForConditionalJoinFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForSimpleLoopFixture`; `OptimizeIRVMEquivalenceHarnessTest#optimizeOnOffMustPreserveObservableTraceForLinearCallFixture` | N/A | pass | Dedicated opt on/off harness with reusable interpreter and deterministic trace assertions is in place. |
|
||||||
| G21-9.2 | Validation MUST preserve known negative loader/verifier behavior. | `BackendSafetyGateSUTest#emitStageMustExposeMarshalingLinkageFailureDeterministically`; `BackendGateIIntegrationTest` rejection suite | N/A | pass | |
|
| G21-9.2 | Validation MUST preserve known negative loader/verifier behavior. | `BackendSafetyGateSUTest#emitStageMustExposeMarshalingLinkageFailureDeterministically`; `BackendGateIIntegrationTest` rejection suite | N/A | pass | |
|
||||||
| G21-9.3 | Validation MUST preserve deterministic artifact-level invariants. | `BackendSafetyGateSUTest#fullPipelineMustProduceDeterministicBytecodeForSameInput`; `BytecodeEmitterTest#emitMustRemainDeterministicAfterInterning` | N/A | pass | |
|
| G21-9.3 | Validation MUST preserve deterministic artifact-level invariants. | `BackendSafetyGateSUTest#fullPipelineMustProduceDeterministicBytecodeForSameInput`; `BytecodeEmitterTest#emitMustRemainDeterministicAfterInterning` | N/A | pass | |
|
||||||
| G23-5.1 | Canonical compiler pipeline MUST preserve the shared stage order through `WriteBytecodeArtifact`. | `MainProjectPipelineIntegrationTest#analyzeShouldNotWriteProgramBytecode`; `MainProjectPipelineIntegrationTest#compileShouldProduceInMemoryBytecodeWithoutWritingProgramBytecode`; `MainProjectPipelineIntegrationTest#buildShouldWriteProgramBytecode` | N/A | partial | Entrypoint execution now covers the full analyze -> compile -> build path, but a dedicated order-only assertion for every terminal boundary is still missing. |
|
| G23-5.1 | Canonical compiler pipeline MUST preserve the shared stage order through `WriteBytecodeArtifact`. | `BuilderPipelineServiceOrderTest#canonicalOrderMustContainOptimizeBetweenLowerAndEmit`; `MainProjectPipelineIntegrationTest#analyzeShouldNotWriteProgramBytecode`; `MainProjectPipelineIntegrationTest#compileShouldProduceInMemoryBytecodeWithoutWritingProgramBytecode`; `MainProjectPipelineIntegrationTest#buildShouldWriteProgramBytecode` | N/A | pass | Dedicated order assertion now covers analyses, compile, and build stage lists, including `AssembleLifecyclePipelineStage`. |
|
||||||
| G23-6.1 | `analyze` MUST terminate after `FrontendPhase` and MUST NOT execute backend artifact stages. | `MainProjectPipelineIntegrationTest#analyzeShouldNotWriteProgramBytecode` | N/A | pass | The integration fixture asserts the analysis snapshot contract and proves `program.pbx` is not written on the analysis path. |
|
| G23-5.2 | `AssembleLifecyclePipelineStage` MUST run immediately after `FrontendPhasePipelineStage` and before IRVM lowering. | `BuilderPipelineServiceOrderTest#canonicalOrderMustContainOptimizeBetweenLowerAndEmit`; `BuilderPipelineServiceOrderTest#analyzeMustTerminateAfterLifecycleAssemblyWithoutBackendArtifacts` | N/A | pass | Analyses terminate at lifecycle assembly; compile stages begin at `LowerToIRVMPipelineStage`. |
|
||||||
|
| G23-6.1 | `analyze` MUST terminate after `AssembleLifecycle` and MUST NOT execute backend artifact stages. | `BuilderPipelineServiceOrderTest#analyzeMustTerminateAfterLifecycleAssemblyWithoutBackendArtifacts`; `MainProjectPipelineIntegrationTest#analyzeShouldNotWriteProgramBytecode` | N/A | pass | Analyze returns an assembled executable `IRBackend` with no IRVM, bytecode, or file output. |
|
||||||
| G23-6.2 | `compile` MUST terminate after `VerifyBytecode` and MUST return a validated in-memory executable result without disk write. | `MainProjectPipelineIntegrationTest#compileShouldProduceInMemoryBytecodeWithoutWritingProgramBytecode`; `BuilderPipelinePublicSurfaceTest#compileResultMustExposeValidatedInMemoryArtifacts` | N/A | pass | Coverage asserts validated in-memory bytecode artifacts and the no-write boundary for `compile`. |
|
| G23-6.2 | `compile` MUST terminate after `VerifyBytecode` and MUST return a validated in-memory executable result without disk write. | `MainProjectPipelineIntegrationTest#compileShouldProduceInMemoryBytecodeWithoutWritingProgramBytecode`; `BuilderPipelinePublicSurfaceTest#compileResultMustExposeValidatedInMemoryArtifacts` | N/A | pass | Coverage asserts validated in-memory bytecode artifacts and the no-write boundary for `compile`. |
|
||||||
| G23-6.3 | `build` MUST extend `compile` only with terminal artifact persistence. | `MainProjectPipelineIntegrationTest#buildShouldWriteProgramBytecode`; `BuilderPipelinePublicSurfaceTest#buildResultMustExposeArtifactPathAndCompilePayload` | N/A | pass | Coverage asserts that `build` retains the compile payload and writes the filesystem artifact path expected by callers. |
|
| G23-6.3 | `build` MUST extend `compile` only with terminal artifact persistence. | `MainProjectPipelineIntegrationTest#buildShouldWriteProgramBytecode`; `BuilderPipelinePublicSurfaceTest#buildResultMustExposeArtifactPathAndCompilePayload` | N/A | pass | Coverage asserts that `build` retains the compile payload and writes the filesystem artifact path expected by callers. |
|
||||||
| G23-7.1 | `AnalysisSnapshot` MUST expose the minimum shared analysis contract. | `MainProjectPipelineIntegrationTest#analyzeShouldNotWriteProgramBytecode`; `BuilderPipelinePublicSurfaceTest#analysisSnapshotMustExposeMinimumSharedContract` | N/A | pass | Both executable and structural contract checks now cover the shared minimum analysis payload. |
|
| G23-7.1 | `AnalysisSnapshot` MUST expose the minimum shared analysis contract. | `MainProjectPipelineIntegrationTest#analyzeShouldNotWriteProgramBytecode`; `BuilderPipelinePublicSurfaceTest#analysisSnapshotMustExposeMinimumSharedContract` | N/A | pass | Both executable and structural contract checks now cover the shared minimum analysis payload. |
|
||||||
| G23-8.1 | Caller-specific configs/contexts MUST NOT redefine canonical stage semantics. | N/A | N/A | missing | Requires explicit multi-entrypoint composition tests once non-filesystem contexts are implemented. |
|
| G23-8.1 | Caller-specific configs/contexts MUST NOT redefine canonical stage semantics. | N/A | N/A | missing | Requires explicit multi-entrypoint composition tests once non-filesystem contexts are implemented. |
|
||||||
|
| G23-8.3 | A compile-only `FrontendProvider` registered by `languageId` MUST traverse `compile()` to verified bytecode without PBS, `.pbs` sources, or PBS stdlib. | `SyntheticFrontendPipelineTest#compileMustEmitVerifiedBytecodeWithoutPbs` | `FrontendRegistryServiceTest#unregisterMustRefuseToRemoveDefaultPbs` | pass | Synthetic `synth` provider is test-only; common pipeline must not require PBS types, PBS sources, or PBS stdlib. |
|
||||||
| G23-9.1 | Legacy public `run` MUST be removed as the normative entrypoint and filesystem-default behavior MUST be expressed through `build`. | `BuilderPipelinePublicSurfaceTest#publicServiceSurfaceMustExposeExplicitEntrypointsAndNoPublicRun`; `MainProjectPipelineIntegrationTest#buildShouldWriteProgramBytecode` | N/A | partial | Public service coverage now proves `run` is no longer public and `build` is the filesystem artifact path, but the CLI composition path is not yet exercised by a dedicated automated test. |
|
| G23-9.1 | Legacy public `run` MUST be removed as the normative entrypoint and filesystem-default behavior MUST be expressed through `build`. | `BuilderPipelinePublicSurfaceTest#publicServiceSurfaceMustExposeExplicitEntrypointsAndNoPublicRun`; `MainProjectPipelineIntegrationTest#buildShouldWriteProgramBytecode` | N/A | partial | Public service coverage now proves `run` is no longer public and `build` is the filesystem artifact path, but the CLI composition path is not yet exercised by a dedicated automated test. |
|
||||||
| PBS13-12.0 | Executable backend handoff MUST satisfy addendum obligations. | `IRBackendExecutableContractTest` suite; `PBSFrontendPhaseServiceTest#shouldSynthesizePositiveTopic19FixtureAcrossFileInitProjectInitAndFrame` | `LowerToIRVMServiceTest#lowerMustRejectWhenSyntheticWrapperEntrypointIsMissing`; `LowerToIRVMServiceTest#lowerMustRejectWhenHiddenBootGuardIsMissing`; `LowerToIRVMServiceTest#lowerMustRejectWhenSyntheticCallableOriginIsMissing` | pass | Row group `PBS13-12.x` details each obligation; topic 19 closure now includes lifecycle wrapper/guard/origin evidence. |
|
| PBS13-12.0 | PBS executable lowering MUST emit `IRBackend` satisfying frontend handoff obligations before common backend lowering. | `IRBackendExecutableContractTest` suite; `PBSFrontendPhaseServiceTest#shouldSynthesizePositiveTopic19FixtureAcrossFileInitProjectInitAndFrame` | `LowerToIRVMServiceTest#lowerMustRejectWhenSyntheticWrapperEntrypointIsMissing`; `LowerToIRVMServiceTest#lowerMustRejectWhenHiddenBootGuardIsMissing`; `LowerToIRVMServiceTest#lowerMustRejectWhenSyntheticCallableOriginIsMissing` | pass | Row group `PBS13-12.x` verifies PBS emission into the common handoff; common backend ownership is covered by G20 rows. |
|
||||||
|
| PBS13-12.7 | PBS executable lowering MUST emit a typed lifecycle declaration and MUST NOT assemble derived wrappers. | `PBSFrontendPhaseServiceTest#shouldSynthesizePositiveTopic19FixtureAcrossFileInitProjectInitAndFrame`; `PbsFrontendCompilerTest#shouldExposeGlobalsAndTypedLifecycleDeclarationInBackendFile` | N/A | pass | Frontend tests assert declaration roles and the absence of module init, published wrapper, and boot guard. |
|
||||||
|
| PBS13-12.8 | Project init MUST be excluded from file-init fragments and MUST execute exactly once after module initializers. | `PbsFrontendCompilerTest#shouldExposeGlobalsAndTypedLifecycleDeclarationInBackendFile`; `LifecycleAssemblerServiceTest#assembleMustInvokeProjectInitExactlyOnceAndExcludeItFromFileInit` | N/A | pass | Colocated `[Init]` is declared as project init and invoked once by the assembled wrapper. |
|
||||||
|
| PBS13-12.9 | Lifecycle module order MUST propagate resolved dependency order without name or `FileId` inference. | `PBSFrontendPhaseServiceTest#shouldPublishDependencyOrderedLifecycleModulesInsteadOfNameOrFileIdOrder`; `IRBackendExecutableContractTest#aggregatorMustRemapTypedLifecycleReferencesAndPreserveDeclaredModuleOrder` | N/A | pass | Adversarial module names and file registration order do not change declared dependency order. |
|
||||||
| PBS13-12.1.1 | Callable identity MUST be preserved at handoff. | `IRBackendExecutableContractTest#aggregatorMustPreserveExecutableFunctionOrderDeterministically` | N/A | pass | |
|
| PBS13-12.1.1 | Callable identity MUST be preserved at handoff. | `IRBackendExecutableContractTest#aggregatorMustPreserveExecutableFunctionOrderDeterministically` | N/A | pass | |
|
||||||
| PBS13-12.1.2 | Observable callable signature MUST be preserved at handoff. | `IRBackendExecutableContractTest#functionContractMustRejectInvalidSlotAndSpanBounds` | N/A | pass | |
|
| PBS13-12.1.2 | Observable callable signature MUST be preserved at handoff. | `IRBackendExecutableContractTest#functionContractMustRejectInvalidSlotAndSpanBounds` | N/A | pass | |
|
||||||
| PBS13-12.1.3 | Callable category MUST be preserved at handoff. | `PbsFrontendCompilerTest#shouldLowerExecutableFunctionsWithCallsiteCategories` | N/A | pass | |
|
| PBS13-12.1.3 | Callable category MUST be preserved at handoff. | `PbsFrontendCompilerTest#shouldLowerExecutableFunctionsWithCallsiteCategories` | N/A | pass | |
|
||||||
@@ -103,7 +124,7 @@ to concrete positive/negative test evidence and current status.
|
|||||||
|
|
||||||
1. Any backend PR that changes conformance-relevant behavior in FE/BE pipeline MUST update this matrix.
|
1. Any backend PR that changes conformance-relevant behavior in FE/BE pipeline MUST update this matrix.
|
||||||
2. If requirement coverage changes, update: mapped tests, status, and `Last Updated` date.
|
2. If requirement coverage changes, update: mapped tests, status, and `Last Updated` date.
|
||||||
3. New normative MUSTs in specs `19/20/21` or PBS `13` addendum MUST add a new matrix row before merge.
|
3. New normative MUSTs in specs `19/20/21` or PBS `13` lowering obligations MUST add a new matrix row before merge.
|
||||||
4. Conformance-relevant FE/BE code paths for hard-gate are:
|
4. Conformance-relevant FE/BE code paths for hard-gate are:
|
||||||
- `prometeu-compiler/prometeu-build-pipeline/`
|
- `prometeu-compiler/prometeu-build-pipeline/`
|
||||||
- `prometeu-compiler/frontends/prometeu-frontend-pbs/`
|
- `prometeu-compiler/frontends/prometeu-frontend-pbs/`
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ Its purpose is to make the compiler usable through explicit entrypoints instead
|
|||||||
This document defines:
|
This document defines:
|
||||||
|
|
||||||
- the canonical stage order shared by compiler entrypoints,
|
- the canonical stage order shared by compiler entrypoints,
|
||||||
|
- the frontend provider and registry boundary used by shared compiler composition,
|
||||||
- the terminal stage and mandatory behavior of `analyze`,
|
- the terminal stage and mandatory behavior of `analyze`,
|
||||||
- the terminal stage and mandatory behavior of `compile`,
|
- the terminal stage and mandatory behavior of `compile`,
|
||||||
- the terminal stage and mandatory behavior of `build`,
|
- the terminal stage and mandatory behavior of `build`,
|
||||||
@@ -25,6 +26,7 @@ This document does not define:
|
|||||||
- one mandatory Java class or package layout,
|
- one mandatory Java class or package layout,
|
||||||
- editor-specific source providers or document-session providers,
|
- editor-specific source providers or document-session providers,
|
||||||
- frontend-specific semantic facts beyond the minimum shared `AnalysisSnapshot` contract,
|
- frontend-specific semantic facts beyond the minimum shared `AnalysisSnapshot` contract,
|
||||||
|
- dynamic frontend plugin discovery,
|
||||||
- or one mandatory CLI architecture.
|
- or one mandatory CLI architecture.
|
||||||
|
|
||||||
## 3. Authority and Precedence
|
## 3. Authority and Precedence
|
||||||
@@ -63,12 +65,13 @@ The canonical stage order is:
|
|||||||
1. `ResolveDepsPipelineStage`
|
1. `ResolveDepsPipelineStage`
|
||||||
2. `LoadSourcesPipelineStage`
|
2. `LoadSourcesPipelineStage`
|
||||||
3. `FrontendPhasePipelineStage`
|
3. `FrontendPhasePipelineStage`
|
||||||
4. `LowerToIRVMPipelineStage`
|
4. `AssembleLifecyclePipelineStage`
|
||||||
5. `OptimizeIRVMPipelineStage`
|
5. `LowerToIRVMPipelineStage`
|
||||||
6. `EmitBytecodePipelineStage`
|
6. `OptimizeIRVMPipelineStage`
|
||||||
7. `LinkBytecodePipelineStage`
|
7. `EmitBytecodePipelineStage`
|
||||||
8. `VerifyBytecodePipelineStage`
|
8. `LinkBytecodePipelineStage`
|
||||||
9. `WriteBytecodeArtifactPipelineStage`
|
9. `VerifyBytecodePipelineStage`
|
||||||
|
10. `WriteBytecodeArtifactPipelineStage`
|
||||||
|
|
||||||
Public entrypoints MAY terminate early according to this document, but they MUST NOT:
|
Public entrypoints MAY terminate early according to this document, but they MUST NOT:
|
||||||
|
|
||||||
@@ -80,21 +83,23 @@ Public entrypoints MAY terminate early according to this document, but they MUST
|
|||||||
|
|
||||||
### 6.1 `analyze`
|
### 6.1 `analyze`
|
||||||
|
|
||||||
`analyze` MUST terminate at `FrontendPhasePipelineStage`.
|
`analyze` MUST terminate at `AssembleLifecyclePipelineStage`.
|
||||||
|
|
||||||
`analyze` is defined as:
|
`analyze` is defined as:
|
||||||
|
|
||||||
1. `ResolveDeps`
|
1. `ResolveDeps`
|
||||||
2. `LoadSources`
|
2. `LoadSources`
|
||||||
3. `FrontendPhase`
|
3. `FrontendPhase`
|
||||||
|
4. `AssembleLifecycle`
|
||||||
|
|
||||||
`analyze` MUST:
|
`analyze` MUST:
|
||||||
|
|
||||||
1. resolve workspace/dependency inputs needed by the frontend,
|
1. resolve workspace/dependency inputs needed by the frontend,
|
||||||
2. load source surfaces admitted by the selected compiler configuration,
|
2. load source surfaces admitted by the selected compiler configuration,
|
||||||
3. run frontend semantic analysis,
|
3. run frontend semantic analysis and emit a declarative `IRBackend`,
|
||||||
4. return an `AnalysisSnapshot` or equivalent result contract,
|
4. assemble the common lifecycle from `IRLifecycleDeclaration` when present,
|
||||||
5. and remain free of backend artifact side effects.
|
5. return an `AnalysisSnapshot` or equivalent result contract whose `IRBackend` is fully assembled when the handoff is executable,
|
||||||
|
6. and remain free of backend artifact side effects.
|
||||||
|
|
||||||
`analyze` MUST NOT:
|
`analyze` MUST NOT:
|
||||||
|
|
||||||
@@ -229,6 +234,88 @@ This authority model MUST NOT:
|
|||||||
2. move semantic inline hint policy into LSP,
|
2. move semantic inline hint policy into LSP,
|
||||||
3. or imply that the host editor may synthesize semantic hints when the frontend did not publish them.
|
3. or imply that the host editor may synthesize semantic hints when the frontend did not publish them.
|
||||||
|
|
||||||
|
## 8.3 Frontend Provider and Registry Contract
|
||||||
|
|
||||||
|
The shared compiler composition surface MUST represent each registered frontend through a `FrontendProvider` or equivalent provider contract.
|
||||||
|
|
||||||
|
At minimum, each provider MUST expose:
|
||||||
|
|
||||||
|
1. `specification()`, returning the frontend-owned static contract, including its stable `languageId`;
|
||||||
|
2. `compiler()`, returning the compiler-facing frontend service used by the shared build pipeline;
|
||||||
|
3. `languageService()`, returning an optional editor-facing language-service capability for tooling consumers.
|
||||||
|
|
||||||
|
`compiler()` is the only required executable frontend capability. It MUST be sufficient for `analyze`, `compile`, `build`, and backend-facing pipeline flows.
|
||||||
|
|
||||||
|
`languageService()` MUST be optional. A frontend that supports compilation but does not provide editor services MUST remain a valid provider. Absence of `languageService()` MUST NOT prevent project analysis, compilation, backend lowering, bytecode emission, verification, or artifact writing.
|
||||||
|
|
||||||
|
The first shared editor-facing contract SHOULD remain an aggregated language-service capability surface. The common compiler contract MUST NOT require separate top-level service interfaces for each editor feature until a future accepted decision and plan identify a real lifecycle, ownership, or testing boundary that requires that split.
|
||||||
|
|
||||||
|
When exposed, editor-facing capabilities MAY include:
|
||||||
|
|
||||||
|
1. diagnostics intended for live editor sessions,
|
||||||
|
2. completion,
|
||||||
|
3. hover,
|
||||||
|
4. definition and navigation,
|
||||||
|
5. signature help,
|
||||||
|
6. semantic tokens for a live document,
|
||||||
|
7. formatting,
|
||||||
|
8. rename,
|
||||||
|
9. code actions,
|
||||||
|
10. and other host-facing editor assistance.
|
||||||
|
|
||||||
|
These capabilities are optional unless a future frontend- or host-specific decision makes one of them mandatory for a narrower surface. Tooling consumers MUST query capability availability before invoking editor-specific behavior.
|
||||||
|
|
||||||
|
Absent editor capabilities MUST have deterministic fallback behavior at tooling boundaries:
|
||||||
|
|
||||||
|
1. collection-shaped responses SHOULD be empty;
|
||||||
|
2. scalar optional responses SHOULD be absent or use a documented neutral response;
|
||||||
|
3. host protocols that can represent unsupported operations SHOULD do so explicitly;
|
||||||
|
4. and absent editor capability MUST NOT be reported as a compiler failure.
|
||||||
|
|
||||||
|
When a frontend exposes definition or navigation, each returned location MUST identify a compiler-known physical source file. A resolved symbol without a physical file MUST produce an empty definition response. Tooling MUST NOT require virtual documents, untitled buffers, or synthetic URIs for this capability.
|
||||||
|
|
||||||
|
When a frontend exposes find-references, each returned usage or declaration location MUST identify a compiler-known physical source file. A cursor offset whose definition response is empty MUST produce an empty references response. Host `includeDeclaration` MAY add the canonical declaration location only when that declaration is a compiler-known physical source file; it MUST NOT invent a virtual, untitled, or synthetic location.
|
||||||
|
|
||||||
|
When a frontend exposes document symbols or outline, the result MUST be the named declaration tree of the requested document. Presence, hierarchy, and ranges MUST come from that document's recovered syntax tree. Semantic success MUST NOT be required. Semantic enrichment MUST NOT drop a named declaration that the syntax tree still exposes. A missing syntax tree MUST produce an empty list. Document symbols MUST NOT be a workspace symbol index, folding ranges, or a navigation list of foreign files.
|
||||||
|
|
||||||
|
When a frontend exposes workspace symbols, the result MUST be a flat search of named declarations whose locations identify compiler-known physical source files of the current analysis. Presence, names, kinds, details, and ranges MUST come from the recovered syntax of those files. Semantic success MUST NOT be required. Semantic enrichment MUST NOT drop a named declaration that the syntax tree still exposes. A missing analysis surface MUST produce an empty list. The workspace-symbol request MUST NOT require an open text document. A declaration without a compiler-known physical file MUST be omitted. Tooling MUST NOT require virtual documents, untitled buffers, or synthetic URIs for this capability. Workspace symbols MUST NOT be a document outline, folding ranges, a persistent symbol index, or a navigation list of virtual locations.
|
||||||
|
|
||||||
|
When a frontend exposes rename, the result MUST be a validated workspace edit of identifier spans whose locations identify compiler-known physical source files. Identity MUST be the physical declaration locations that definition returns at the cursor. A local or parameter name span MUST still be renameable when definition at that offset is empty. Each rewritten location MUST identify a compiler-known physical source file. A cursor that is not renameable, including builtins, virtual paths, unresolved names, keywords, comments, strings, import aliases and uses of those aliases, error case labels without their own span, and barrel files, MUST produce a protocol error or a null prepareRename result. Tooling MUST NOT return a successful empty workspace edit for a refused cursor or an invalid new name. The new name MUST be a language identifier that is not a keyword and MUST NOT collide in the same binding space, ignoring the sites being rewritten and the overload set being renamed. The server MUST NOT write files and MUST NOT rename file paths. Host prepareRename MUST advertise a prepareProvider when rename is exposed. Tooling MUST NOT require virtual documents, untitled buffers, or synthetic URIs for this capability.
|
||||||
|
|
||||||
|
When a frontend exposes code actions, the result MUST be quick fixes only: one workspace edit tied to a diagnostic of the requested physical document. The frontend MUST produce each repair from that document's syntax. Each repair MUST name the stable diagnostic code, the primary span, and exactly one local text edit. Tooling MUST transport that repair. Tooling MUST NOT choose the edit by parsing the diagnostic message or by a diagnostic-code table. A repair MUST NOT be a required field of compiler diagnostics and MUST NOT be published inside diagnostic data. The published diagnostic MUST carry the stable code so a later code-action request can match it. A repair MUST be returned only when the request context contains a diagnostic with the same code and the same primary range. An empty diagnostic context MUST produce an empty list. The edit MUST change only the requested physical source file. The server MUST NOT write files, MUST NOT return a command, and MUST NOT require a resolve round trip. A missing code-action capability MUST NOT advertise code actions and MUST produce an empty list rather than a protocol error. Virtual, untitled, or synthetic documents MUST NOT receive an edit. Code actions MUST NOT include organize-imports, source actions, refactors, or generated stubs unless a future accepted decision says so.
|
||||||
|
|
||||||
|
Compiler diagnostics and editor diagnostics are distinct ownership surfaces. Diagnostics returned by `analyze`, `compile`, and `build` are compiler contract output. Editor diagnostics MAY reuse compiler analysis results, live overlays, caches, or cancellation-aware tooling state, but a frontend MUST NOT be required to provide editor diagnostics in order to compile.
|
||||||
|
|
||||||
|
When tooling publishes an editor diagnostic, `source` MUST be the `languageId` of the bound frontend project. `code` MUST be the stable compiler diagnostic code when one exists, and MUST be empty when the compiler diagnostic has none. Tooling MUST NOT copy that code into `source`. Tooling MUST NOT publish related locations, compiler phase, or a repair payload on the editor diagnostic.
|
||||||
|
|
||||||
|
When a frontend exposes document links, each link MUST cover the span of a module reference whose resolved destination is a compiler-known regular file. A module reference that does not resolve to a regular file MUST produce no link. Tooling MUST NOT target virtual, untitled, or synthetic URIs, including virtual stdlib documents. Document links MUST NOT replace definition. A missing document-link capability MUST NOT be advertised and MUST produce an empty list rather than a protocol error.
|
||||||
|
|
||||||
|
When a frontend exposes folding ranges, the ranges MUST come from recovered syntax spans for top-level `fn`, `struct`, `service`, `contract`, `enum`, `error`, `callback`, and `host` declarations, their bodies, and `Doc` text blocks. A parameter list MUST fold from the parenthesis pair. A brace, parenthesis, or text-block delimiter that the recovered tree does not cover MUST still produce a token range, including an unmatched opener through the end of the text. Folding ranges MUST NOT be document symbols.
|
||||||
|
|
||||||
|
When a frontend exposes selection ranges, the chain at a cursor MUST run from the inside outward in this order: identifier, argument or parameter list, block or `Doc` text block, declaration. A layer that does not contain the cursor MUST be omitted. A missing folding or selection capability MUST NOT be advertised and MUST produce an empty list rather than a protocol error.
|
||||||
|
|
||||||
|
When a frontend exposes call hierarchy, incoming and outgoing calls MUST be callsites found by walking call expressions in the syntax tree. The references index MUST NOT be used as the call graph. A cursor that is not on a function, method, or constructor MUST produce an empty prepare result. Type hierarchy MUST NOT be advertised. A missing call-hierarchy capability MUST NOT be advertised and MUST produce an empty list rather than a protocol error.
|
||||||
|
|
||||||
|
When a frontend exposes completion inside a module reference, the candidates MUST be project and stdlib modules the current module resolver can already name. Completion outside a module reference MUST keep its existing member and general candidates. Completion items MUST stay eager. `resolveProvider` MUST stay false. Snippets and a new ranking score MUST NOT be added.
|
||||||
|
|
||||||
|
When a frontend exposes semantic tokens, the lexical token provider remains the baseline. An identifier token MAY be replaced with an existing semantic key when the same resolution used by hover names that symbol and an existing key matches it. Resolution failure, a broken file, or a symbol with no existing key MUST keep the baseline token. This overlay MUST NOT add a semantic-token key.
|
||||||
|
|
||||||
|
When a frontend exposes formatting, it MUST be full-document formatting only. Range formatting and on-type formatting MUST NOT be advertised. The formatter MUST reprint the existing token stream. It MUST NOT reorder declarations, join lines, or split lines. Indentation MUST be four spaces and MUST change only where brace or parenthesis nesting changes. The interior of a `Doc` text block MUST be copied unchanged. A comment MUST stay on the line of the token it already follows. A missing formatting capability MUST NOT be advertised and MUST produce an empty edit list rather than a protocol error.
|
||||||
|
|
||||||
|
`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.
|
||||||
|
|
||||||
|
The frontend registry MUST resolve providers by `languageId`. A lookup for an unknown `languageId` MUST fail explicitly with a diagnostic-friendly error. Unknown languages MUST NOT silently fall back to PBS or to any other frontend.
|
||||||
|
|
||||||
|
Common compiler, build pipeline, and Studio-facing consumers MUST obtain frontend behavior through provider lookup. They MUST NOT directly instantiate frontend-specific compiler services, except inside the frontend provider itself or inside an approved application composition root.
|
||||||
|
|
||||||
|
Provider registration MUST be explicit in v1. The registry contract MUST NOT use dynamic plugin discovery, reflection-based discovery, classpath scanning, external JAR loading, or runtime plugin installation to discover frontends.
|
||||||
|
|
||||||
|
PBS is the only initial real provider for this contract. PBS MAY be registered by an application composition root, but PBS MUST NOT become an exclusive semantic owner of the shared compiler pipeline.
|
||||||
|
|
||||||
|
A compile-only `FrontendProvider` registered by `languageId` MUST be a valid participant of `analyze`, `compile`, and `build`. The shared pipeline MUST NOT require PBS frontend types, `.pbs` or `.barrel` sources, or PBS stdlib in order to emit verified bytecode. Test-only frontends MAY exist solely as fixtures. They MUST NOT be product languages, MUST NOT be registered by default bootstrap or Studio composition, and MUST NOT be discovered by plugin scanning, classpath scanning, or external JAR loading.
|
||||||
|
|
||||||
|
The frontend registry MUST expose explicit `register` and `unregister` operations. `unregister` MUST refuse to remove the default PBS provider. Lookup of an unknown `languageId` MUST fail explicitly. `unregister` of an unknown `languageId` MUST be a no-op.
|
||||||
|
|
||||||
## 9. Public Surface Rule
|
## 9. Public Surface Rule
|
||||||
|
|
||||||
The shared compiler public surface MUST expose explicit entrypoints equivalent in meaning to:
|
The shared compiler public surface MUST expose explicit entrypoints equivalent in meaning to:
|
||||||
|
|||||||
@@ -121,6 +121,11 @@ Rules:
|
|||||||
- glyph-bank palette payloads must expose canonical `rgba8888` color values in runtime RGBA channel order;
|
- glyph-bank palette payloads must expose canonical `rgba8888` color values in runtime RGBA channel order;
|
||||||
- ARGB values produced by host image APIs are import-side implementation details, not canonical declaration or projection fields;
|
- ARGB values produced by host image APIs are import-side implementation details, not canonical declaration or projection fields;
|
||||||
- `convertedRgb565` is not part of the normal palette contract;
|
- `convertedRgb565` is not part of the normal palette contract;
|
||||||
|
- glyph-bank `palette_count` is an effective runtime metadata field and means
|
||||||
|
the number of serialized and resident RGBA8888 palettes for the bank;
|
||||||
|
- glyph-bank `palette_count` must be in the inclusive range `1..=64`;
|
||||||
|
- `palette_authored`, when present, is informative tooling metadata only and
|
||||||
|
must not be treated as runtime-effective metadata;
|
||||||
- the packer must sort such entries by numeric `index`, not by physical array position;
|
- the packer must sort such entries by numeric `index`, not by physical array position;
|
||||||
- duplicate or malformed indices are structural errors;
|
- duplicate or malformed indices are structural errors;
|
||||||
- missing or malformed `palette` payloads are structural errors;
|
- missing or malformed `palette` payloads are structural errors;
|
||||||
|
|||||||
@@ -147,7 +147,8 @@ Offset ambiguity guardrail:
|
|||||||
|
|
||||||
## Format-Specific Baseline: `GLYPH/indexed_v1`
|
## Format-Specific Baseline: `GLYPH/indexed_v1`
|
||||||
|
|
||||||
The first-wave producer contract for `GLYPH/indexed_v1` is fixed and runtime-aligned.
|
The producer contract for `GLYPH/indexed_v1` is runtime-aligned and uses a
|
||||||
|
variable RGBA8888 palette block.
|
||||||
|
|
||||||
### Tile Selection and Identity
|
### Tile Selection and Identity
|
||||||
|
|
||||||
@@ -178,7 +179,7 @@ Rules:
|
|||||||
|
|
||||||
- the serialized payload for `GLYPH/indexed_v1` is:
|
- the serialized payload for `GLYPH/indexed_v1` is:
|
||||||
1. one packed `u4` pixel plane for the full emitted sheet;
|
1. one packed `u4` pixel plane for the full emitted sheet;
|
||||||
2. one palette block of `64 * 16 * 4 = 4096` bytes;
|
2. one palette block of `palette_count * 16 * 4` bytes;
|
||||||
- packed pixel bytes must be emitted by the packer, not inferred later by the runtime;
|
- packed pixel bytes must be emitted by the packer, not inferred later by the runtime;
|
||||||
- the palette block is serialized as RGBA8888 values in runtime RGBA channel order;
|
- the palette block is serialized as RGBA8888 values in runtime RGBA channel order;
|
||||||
- each palette entry is emitted as four bytes in `R`, `G`, `B`, `A` order;
|
- each palette entry is emitted as four bytes in `R`, `G`, `B`, `A` order;
|
||||||
@@ -196,10 +197,15 @@ Rules:
|
|||||||
- `width`
|
- `width`
|
||||||
- `height`
|
- `height`
|
||||||
- `palette_count`
|
- `palette_count`
|
||||||
- tile-bank v1 requires `palette_count = 64`;
|
- tile-bank v1 requires `palette_count` in the inclusive range `1..=64`;
|
||||||
|
- `palette_count` is the number of serialized palettes and resident runtime
|
||||||
|
palettes for the bank;
|
||||||
- tile-bank v1 size formulas are:
|
- tile-bank v1 size formulas are:
|
||||||
- `size = ceil(width * height / 2) + 4096`
|
- `size = ceil(width * height / 2) + palette_count * 16 * 4`
|
||||||
- `decoded_size = (width * height) + 4096`
|
- `decoded_size = (width * height) + palette_count * 16 * 4`
|
||||||
|
- fixed 64-palette padding is not a compatibility mode unless
|
||||||
|
`palette_count = 64` and the payload directly satisfies the v1 contract;
|
||||||
|
- `GLYPH/indexed_v2` must not be introduced for this palette-count correction.
|
||||||
|
|
||||||
### Palette Contract
|
### Palette Contract
|
||||||
|
|
||||||
@@ -209,7 +215,8 @@ Rules:
|
|||||||
- each palette declaration uses the shape `{ "index": <int>, "palette": { ... } }`;
|
- each palette declaration uses the shape `{ "index": <int>, "palette": { ... } }`;
|
||||||
- each palette payload uses canonical `rgba8888` entries interpreted as `0xRRGGBBAA`;
|
- each palette payload uses canonical `rgba8888` entries interpreted as `0xRRGGBBAA`;
|
||||||
- palette ordering is ascending numeric `index`, never raw array position;
|
- palette ordering is ascending numeric `index`, never raw array position;
|
||||||
- palette ids in the emitted glyph bank are the normalized declared palette indices;
|
- palette ids in the emitted glyph bank are direct declared palette indices;
|
||||||
|
- v1 has no sparse-to-dense palette remapping metadata;
|
||||||
- palette index `0` is ordinary and may carry any RGBA8888 value;
|
- palette index `0` is ordinary and may carry any RGBA8888 value;
|
||||||
- glyph palettes have 16 usable entries;
|
- glyph palettes have 16 usable entries;
|
||||||
- transparency and partial transparency are encoded only by RGBA alpha;
|
- transparency and partial transparency are encoded only by RGBA alpha;
|
||||||
|
|||||||
@@ -226,6 +226,11 @@ Rules:
|
|||||||
- `preload`
|
- `preload`
|
||||||
- Glyph-bank palette projections must use canonical `rgba8888` values when
|
- Glyph-bank palette projections must use canonical `rgba8888` values when
|
||||||
palette data is shown.
|
palette data is shown.
|
||||||
|
- Glyph-bank runtime output projections must present `palette_count`, when
|
||||||
|
shown, as the runtime-effective serialized and resident palette count in
|
||||||
|
`1..=64`.
|
||||||
|
- Studio-facing glyph palette views must not present `palette_authored` as the
|
||||||
|
runtime-effective count.
|
||||||
- Studio-facing glyph palette views must not expose `convertedRgb565` as normal
|
- Studio-facing glyph palette views must not expose `convertedRgb565` as normal
|
||||||
runtime or tooling truth.
|
runtime or tooling truth.
|
||||||
- Runtime-facing output information must not require raw JSON inspection.
|
- Runtime-facing output information must not require raw JSON inspection.
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ Scope boundary:
|
|||||||
- PROMETEU itself is a fantasy handheld / fantasy console with a broader machine model, firmware model, cartridge model, and virtual hardware surface.
|
- PROMETEU itself is a fantasy handheld / fantasy console with a broader machine model, firmware model, cartridge model, and virtual hardware surface.
|
||||||
- This document does not define the whole PROMETEU machine.
|
- This document does not define the whole PROMETEU machine.
|
||||||
- This document defines the VM/runtime subsystem that executes bytecode inside that machine.
|
- This document defines the VM/runtime subsystem that executes bytecode inside that machine.
|
||||||
- For broader machine-level framing, see [`../specs/README.md`](../specs/README.md).
|
- For broader machine-level framing, see [`../specs/README.md`](../specs/runtime/README.md).
|
||||||
|
|
||||||
Document roles:
|
Document roles:
|
||||||
|
|
||||||
@@ -149,6 +149,7 @@ The verifier statically checks bytecode for structural safety and stack‑shape
|
|||||||
- `SyscallMeta` defines expected arity and return slot counts. The loader resolves `HOSTCALL` against this metadata and rejects raw `SYSCALL` in PBX pre-load artifacts; the verifier checks final IDs/arity/return‑slot counts against the same metadata.
|
- `SyscallMeta` defines expected arity and return slot counts. The loader resolves `HOSTCALL` against this metadata and rejects raw `SYSCALL` in PBX pre-load artifacts; the verifier checks final IDs/arity/return‑slot counts against the same metadata.
|
||||||
- Arguments and returns
|
- Arguments and returns
|
||||||
- Arguments are taken from the operand stack in the order defined by the ABI. Returns use multi‑slot results via a host‑side return buffer (`HostReturn`) which the VM copies back onto the stack, or zero slots for “void”. A mismatch in result counts is a fault/panic per current hardening logic.
|
- Arguments are taken from the operand stack in the order defined by the ABI. Returns use multi‑slot results via a host‑side return buffer (`HostReturn`) which the VM copies back onto the stack, or zero slots for “void”. A mismatch in result counts is a fault/panic per current hardening logic.
|
||||||
|
- Example: the canonical asset runtime load surface is `asset.load(asset_id, slot) -> (status, handle)`. The caller does not supply `asset_name` or `asset_type`; bank kind is derived from `asset_table` using `asset_id`.
|
||||||
- Capabilities
|
- Capabilities
|
||||||
- Cartridge capability flags are applied before load-time host resolution. Missing required capability aborts load; invoking a syscall without the required capability also traps defensively at runtime.
|
- Cartridge capability flags are applied before load-time host resolution. Missing required capability aborts load; invoking a syscall without the required capability also traps defensively at runtime.
|
||||||
|
|
||||||
|
|||||||
@@ -78,6 +78,17 @@ Authority rule:
|
|||||||
- `INTRINSIC u32` — final numeric VM-owned intrinsic call.
|
- `INTRINSIC u32` — final numeric VM-owned intrinsic call.
|
||||||
- `FRAME_SYNC` — yield until the next frame boundary (e.g., vblank); explicit safepoint.
|
- `FRAME_SYNC` — yield until the next frame boundary (e.g., vblank); explicit safepoint.
|
||||||
|
|
||||||
|
Host service arity is not encoded in the opcode itself. It is defined by resolved syscall metadata.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
- `asset.load` currently resolves with `arg_slots = 2` and `ret_slots = 2`.
|
||||||
|
- The canonical stack contract is `asset_id, slot -> status, handle`.
|
||||||
|
- Callers do not provide an explicit asset kind; the runtime derives it from `asset_table`.
|
||||||
|
- `composer.bind_scene` resolves with `arg_slots = 1` and `ret_slots = 1`.
|
||||||
|
- The canonical stack contract is `bank_id -> status`.
|
||||||
|
- `composer.emit_sprite` resolves with `arg_slots = 9` and `ret_slots = 1`.
|
||||||
|
|
||||||
#### Canonical Intrinsic Registry Artifact
|
#### Canonical Intrinsic Registry Artifact
|
||||||
|
|
||||||
- Final intrinsic IDs and intrinsic stack metadata are published in [`INTRINSICS.csv`](INTRINSICS.csv).
|
- Final intrinsic IDs and intrinsic stack metadata are published in [`INTRINSICS.csv`](INTRINSICS.csv).
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# VM Architecture Mirror Policy
|
||||||
|
|
||||||
|
The Prometeu runtime repository is the normative authority for PBX binary
|
||||||
|
layout, Core ISA, loader behavior, verification, and PVM execution semantics.
|
||||||
|
The files in this directory are convenience mirrors for Studio-side compiler
|
||||||
|
and integration work; they are not an independent architectural authority.
|
||||||
|
|
||||||
|
Canonical runtime sources:
|
||||||
|
|
||||||
|
- `../runtime/docs/vm-arch/ARCHITECTURE.md`
|
||||||
|
- `../runtime/docs/vm-arch/ISA_CORE.md`
|
||||||
|
- `../runtime/docs/vm-arch/INTRINSICS.csv`
|
||||||
|
|
||||||
|
When these mirrors are retained, an integration change that updates a canonical
|
||||||
|
runtime source MUST update the corresponding Studio mirror in the same logical
|
||||||
|
change. Verify synchronization from the Studio repository root with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
diff -u docs/vm-arch/ARCHITECTURE.md ../runtime/docs/vm-arch/ARCHITECTURE.md
|
||||||
|
diff -u docs/vm-arch/ISA_CORE.md ../runtime/docs/vm-arch/ISA_CORE.md
|
||||||
|
diff -u docs/vm-arch/INTRINSICS.csv ../runtime/docs/vm-arch/INTRINSICS.csv
|
||||||
|
```
|
||||||
|
|
||||||
|
All three commands MUST exit successfully with no output before a change claims
|
||||||
|
that the mirrors are synchronized. If the runtime repository is not available
|
||||||
|
in the same checkout, synchronization evidence must be produced against the
|
||||||
|
canonical runtime revision before merging.
|
||||||
|
|
||||||
|
Compiler-owned transformation contracts remain under `docs/specs/compiler`.
|
||||||
|
Those specifications define `IRBackend -> IRVM -> PBX` emission, but they MUST
|
||||||
|
conform to the runtime-owned PBX and ISA contracts and MUST NOT redefine runtime
|
||||||
|
execution semantics.
|
||||||
@@ -5,6 +5,7 @@ jackson = "2.18.2"
|
|||||||
jacoco = "0.8.12"
|
jacoco = "0.8.12"
|
||||||
lombok = "1.18.32"
|
lombok = "1.18.32"
|
||||||
junit-jupiter = "5.12.1"
|
junit-jupiter = "5.12.1"
|
||||||
|
archunit = "1.4.2"
|
||||||
slf4j = "2.0.7"
|
slf4j = "2.0.7"
|
||||||
lsp4j = "1.0.0"
|
lsp4j = "1.0.0"
|
||||||
|
|
||||||
@@ -19,6 +20,7 @@ apache-commons-collections = { group = "org.apache.commons", name = "commons-col
|
|||||||
jacoco-core = { group = "org.jacoco", name = "org.jacoco.core", version.ref = "jacoco" }
|
jacoco-core = { group = "org.jacoco", name = "org.jacoco.core", version.ref = "jacoco" }
|
||||||
lombok = { group = "org.projectlombok", name = "lombok", version.ref = "lombok" }
|
lombok = { group = "org.projectlombok", name = "lombok", version.ref = "lombok" }
|
||||||
junit-jupiter = { group = "org.junit.jupiter", name = "junit-jupiter", version.ref = "junit-jupiter" }
|
junit-jupiter = { group = "org.junit.jupiter", name = "junit-jupiter", version.ref = "junit-jupiter" }
|
||||||
|
archunit-junit5 = { group = "com.tngtech.archunit", name = "archunit-junit5", version.ref = "archunit" }
|
||||||
slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" }
|
slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" }
|
||||||
slf4j-simple = { group = "org.slf4j", name = "slf4j-simple", version.ref = "slf4j" }
|
slf4j-simple = { group = "org.slf4j", name = "slf4j-simple", version.ref = "slf4j" }
|
||||||
lsp4j = { group = "org.eclipse.lsp4j", name = "org.eclipse.lsp4j", version.ref = "lsp4j" }
|
lsp4j = { group = "org.eclipse.lsp4j", name = "org.eclipse.lsp4j", version.ref = "lsp4j" }
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ dependencies {
|
|||||||
implementation(project(":prometeu-infra"))
|
implementation(project(":prometeu-infra"))
|
||||||
implementation(project(":prometeu-lsp:prometeu-lsp-api"))
|
implementation(project(":prometeu-lsp:prometeu-lsp-api"))
|
||||||
implementation(project(":prometeu-lsp:prometeu-lsp-v1"))
|
implementation(project(":prometeu-lsp:prometeu-lsp-v1"))
|
||||||
|
implementation(project(":prometeu-compiler:prometeu-frontend-registry"))
|
||||||
implementation(project(":prometeu-packer:prometeu-packer-api"))
|
implementation(project(":prometeu-packer:prometeu-packer-api"))
|
||||||
implementation(project(":prometeu-packer:prometeu-packer-v1"))
|
implementation(project(":prometeu-packer:prometeu-packer-v1"))
|
||||||
implementation(project(":prometeu-studio"))
|
implementation(project(":prometeu-studio"))
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package p.studio;
|
|||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import p.packer.Packer;
|
import p.packer.Packer;
|
||||||
|
import p.studio.compiler.FrontendRegistryService;
|
||||||
import p.studio.lsp.api.LspServerLifecycle;
|
import p.studio.lsp.api.LspServerLifecycle;
|
||||||
import p.studio.lsp.events.StudioEventBus;
|
import p.studio.lsp.events.StudioEventBus;
|
||||||
import p.studio.lsp.events.StudioPackerEventAdapter;
|
import p.studio.lsp.events.StudioPackerEventAdapter;
|
||||||
@@ -24,6 +25,7 @@ public final class AppContainer implements Container {
|
|||||||
private final LspServerLifecycle lspServerLifecycle;
|
private final LspServerLifecycle lspServerLifecycle;
|
||||||
|
|
||||||
public AppContainer() {
|
public AppContainer() {
|
||||||
|
FrontendRegistryService.bootstrapDefaults();
|
||||||
this.i18nService = new I18nService();
|
this.i18nService = new I18nService();
|
||||||
this.themeService = new ThemeService();
|
this.themeService = new ThemeService();
|
||||||
this.studioEventBus = new StudioEventBus();
|
this.studioEventBus = new StudioEventBus();
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
plugins {
|
||||||
|
id("gradle.java-library-conventions")
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
testImplementation(libs.archunit.junit5)
|
||||||
|
|
||||||
|
testImplementation(project(":prometeu-compiler:frontends:prometeu-frontend-pbs"))
|
||||||
|
testImplementation(project(":prometeu-compiler:prometeu-frontend-registry"))
|
||||||
|
testImplementation(project(":prometeu-compiler:prometeu-compiler-core"))
|
||||||
|
testImplementation(project(":prometeu-compiler:prometeu-frontend-api"))
|
||||||
|
testImplementation(project(":prometeu-compiler:prometeu-build-pipeline"))
|
||||||
|
testImplementation(project(":prometeu-compiler:prometeu-deps"))
|
||||||
|
testImplementation(project(":prometeu-infra"))
|
||||||
|
testImplementation(project(":prometeu-lsp:prometeu-lsp-api"))
|
||||||
|
testImplementation(project(":prometeu-lsp:prometeu-lsp-v1"))
|
||||||
|
testImplementation(project(":prometeu-studio"))
|
||||||
|
testImplementation(project(":prometeu-app"))
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named<JacocoReport>("jacocoTestReport") {
|
||||||
|
enabled = false
|
||||||
|
}
|
||||||
+63
@@ -0,0 +1,63 @@
|
|||||||
|
package p.studio.architecture;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
|
class CommonBackendPbsPrefixScanTest {
|
||||||
|
private static final String COMPILER_SOURCE_ROOT =
|
||||||
|
"prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler";
|
||||||
|
private static final List<String> GUARDED_RELATIVE_ROOTS = List.of(
|
||||||
|
"backend",
|
||||||
|
"lifecycle",
|
||||||
|
"workspaces/stages");
|
||||||
|
private static final String FORBIDDEN_PBS_PREFIX = "__pbs.";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void commonLifecycleAndBackendMustNotDiscoverRolesFromPbsNamePrefixes() throws IOException {
|
||||||
|
final var violations = new ArrayList<String>();
|
||||||
|
final var repoRoot = locateRepoRoot();
|
||||||
|
final var compilerRoot = repoRoot.resolve(COMPILER_SOURCE_ROOT);
|
||||||
|
for (final var relativeRoot : GUARDED_RELATIVE_ROOTS) {
|
||||||
|
final var root = compilerRoot.resolve(relativeRoot);
|
||||||
|
if (!Files.exists(root)) {
|
||||||
|
fail("guarded source root is missing: " + root);
|
||||||
|
}
|
||||||
|
try (final var paths = Files.walk(root)) {
|
||||||
|
paths.filter(path -> path.toString().endsWith(".java")).forEach(path -> {
|
||||||
|
try {
|
||||||
|
if (Files.readString(path).contains(FORBIDDEN_PBS_PREFIX)) {
|
||||||
|
violations.add(repoRoot.relativize(path).toString());
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException("failed to read source file: " + path, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(
|
||||||
|
violations.isEmpty(),
|
||||||
|
"common lifecycle/backend code must not inspect __pbs. prefixes: " + violations);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Path locateRepoRoot() {
|
||||||
|
var cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize();
|
||||||
|
while (cursor != null) {
|
||||||
|
final var hasDocs = Files.isDirectory(cursor.resolve("docs/specs/compiler"));
|
||||||
|
final var hasCompiler = Files.isDirectory(cursor.resolve("prometeu-compiler"));
|
||||||
|
if (hasDocs && hasCompiler) {
|
||||||
|
return cursor;
|
||||||
|
}
|
||||||
|
cursor = cursor.getParent();
|
||||||
|
}
|
||||||
|
fail("could not locate repository root from working directory");
|
||||||
|
throw new IllegalStateException("unreachable");
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package p.studio.architecture;
|
||||||
|
|
||||||
|
import com.tngtech.archunit.base.DescribedPredicate;
|
||||||
|
import com.tngtech.archunit.core.domain.JavaClass;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
final class DescribedPredicates {
|
||||||
|
private DescribedPredicates() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static DescribedPredicate<JavaClass> notBelongingTo(final Class<?>... allowed) {
|
||||||
|
final Set<String> allowedNames = Arrays.stream(allowed)
|
||||||
|
.map(Class::getName)
|
||||||
|
.collect(Collectors.toUnmodifiableSet());
|
||||||
|
return DescribedPredicate.describe(
|
||||||
|
"do not belong to " + allowedNames,
|
||||||
|
javaClass -> !allowedNames.contains(javaClass.getName()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+85
@@ -0,0 +1,85 @@
|
|||||||
|
package p.studio.architecture;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
|
class PbsGradleDependencyAllowlistTest {
|
||||||
|
private static final Pattern PBS_PROJECT_DEP = Pattern.compile(
|
||||||
|
"(\\w+)\\(\\s*project\\(\\s*\"" + Pattern.quote(PbsModuleOrigins.PBS_GRADLE_PATH) + "\"\\s*\\)");
|
||||||
|
private static final Map<String, Set<String>> ALLOWED_CONFIGURATIONS = Map.of(
|
||||||
|
":prometeu-compiler:prometeu-frontend-registry", Set.of("implementation", "api"),
|
||||||
|
":prometeu-architecture-tests", Set.of("testImplementation"));
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void onlyAllowlistedProjectsMayDependOnThePbsFrontendModule() throws IOException {
|
||||||
|
final var repoRoot = locateRepoRoot();
|
||||||
|
final var violations = new ArrayList<String>();
|
||||||
|
|
||||||
|
try (final var paths = Files.walk(repoRoot)) {
|
||||||
|
paths.filter(path -> path.getFileName().toString().equals("build.gradle.kts"))
|
||||||
|
.filter(path -> !path.toString().contains("/buildSrc/"))
|
||||||
|
.filter(path -> !path.toString().contains("/build/"))
|
||||||
|
.forEach(path -> collectViolations(repoRoot, path, violations));
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(violations.isEmpty(), "PBS Gradle project dependency allowlist violated: " + violations);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void collectViolations(
|
||||||
|
final Path repoRoot,
|
||||||
|
final Path buildFile,
|
||||||
|
final ArrayList<String> violations) {
|
||||||
|
final var projectPath = toProjectPath(repoRoot, buildFile);
|
||||||
|
if (PbsModuleOrigins.PBS_GRADLE_PATH.equals(projectPath)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final String content;
|
||||||
|
try {
|
||||||
|
content = Files.readString(buildFile);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException("failed to read " + buildFile, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
final var matcher = PBS_PROJECT_DEP.matcher(content);
|
||||||
|
while (matcher.find()) {
|
||||||
|
final var configuration = matcher.group(1);
|
||||||
|
final var allowed = ALLOWED_CONFIGURATIONS.getOrDefault(projectPath, Set.of());
|
||||||
|
if (!allowed.contains(configuration)) {
|
||||||
|
violations.add(projectPath + " " + configuration + " " + PbsModuleOrigins.PBS_GRADLE_PATH);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String toProjectPath(final Path repoRoot, final Path buildFile) {
|
||||||
|
final var relative = repoRoot.relativize(buildFile.getParent()).toString().replace('\\', '/');
|
||||||
|
if (relative.isEmpty() || ".".equals(relative)) {
|
||||||
|
return ":";
|
||||||
|
}
|
||||||
|
return ":" + relative.replace('/', ':');
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Path locateRepoRoot() {
|
||||||
|
var cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize();
|
||||||
|
while (cursor != null) {
|
||||||
|
final var hasDocs = Files.isDirectory(cursor.resolve("docs/specs/compiler"));
|
||||||
|
final var hasCompiler = Files.isDirectory(cursor.resolve("prometeu-compiler"));
|
||||||
|
if (hasDocs && hasCompiler) {
|
||||||
|
return cursor;
|
||||||
|
}
|
||||||
|
cursor = cursor.getParent();
|
||||||
|
}
|
||||||
|
fail("could not locate repository root from working directory");
|
||||||
|
throw new IllegalStateException("unreachable");
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package p.studio.architecture;
|
||||||
|
|
||||||
|
import com.tngtech.archunit.core.importer.ImportOption;
|
||||||
|
import com.tngtech.archunit.junit.AnalyzeClasses;
|
||||||
|
import com.tngtech.archunit.junit.ArchTest;
|
||||||
|
import com.tngtech.archunit.lang.ArchRule;
|
||||||
|
import p.studio.compiler.PBSDefinitions;
|
||||||
|
import p.studio.compiler.PBSFrontendProvider;
|
||||||
|
|
||||||
|
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
|
||||||
|
import static p.studio.architecture.PbsModuleOrigins.fromFrontendApiModule;
|
||||||
|
import static p.studio.architecture.PbsModuleOrigins.fromPbsModule;
|
||||||
|
import static p.studio.architecture.PbsModuleOrigins.fromRegistryModule;
|
||||||
|
|
||||||
|
@AnalyzeClasses(packages = "p.studio", importOptions = ImportOption.DoNotIncludeTests.class)
|
||||||
|
class PbsModuleBoundaryArchTest {
|
||||||
|
|
||||||
|
@ArchTest
|
||||||
|
static final ArchRule productionOutsideAllowlistMustNotDependOnPbsModuleTypes = noClasses()
|
||||||
|
.that(fromPbsModule().negate())
|
||||||
|
.and(fromRegistryModule().negate())
|
||||||
|
.should()
|
||||||
|
.dependOnClassesThat(fromPbsModule())
|
||||||
|
.because("DEC-0050: only prometeu-frontend-pbs and prometeu-frontend-registry may depend on PBS module types");
|
||||||
|
|
||||||
|
@ArchTest
|
||||||
|
static final ArchRule registryMustOnlyDependOnPbsProviderFacade = noClasses()
|
||||||
|
.that(fromRegistryModule())
|
||||||
|
.should()
|
||||||
|
.dependOnClassesThat(
|
||||||
|
fromPbsModule()
|
||||||
|
.and(DescribedPredicates.notBelongingTo(PBSFrontendProvider.class, PBSDefinitions.class)))
|
||||||
|
.because("DEC-0050: registry may depend only on PBSFrontendProvider and PBSDefinitions");
|
||||||
|
|
||||||
|
@ArchTest
|
||||||
|
static final ArchRule irBackendModelsMustNotDependOnPbsModuleTypes = noClasses()
|
||||||
|
.that(fromFrontendApiModule())
|
||||||
|
.and()
|
||||||
|
.resideInAPackage("p.studio.compiler.models..")
|
||||||
|
.should()
|
||||||
|
.dependOnClassesThat(fromPbsModule())
|
||||||
|
.because("DEC-0050: public IRBackend contract types must not depend on PBS module types");
|
||||||
|
}
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
package p.studio.architecture;
|
||||||
|
|
||||||
|
import com.tngtech.archunit.core.importer.ClassFileImporter;
|
||||||
|
import com.tngtech.archunit.core.importer.ImportOption;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
|
class PbsModuleClasspathTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void importerMustSeePbsAndRegistryModuleOrigins() {
|
||||||
|
final var classes = new ClassFileImporter()
|
||||||
|
.withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
|
||||||
|
.importPackages("p.studio");
|
||||||
|
|
||||||
|
final var pbsSample = classes.stream()
|
||||||
|
.filter(PbsModuleOrigins::isPbsModule)
|
||||||
|
.findFirst();
|
||||||
|
final var registrySample = classes.stream()
|
||||||
|
.filter(PbsModuleOrigins::isRegistryModule)
|
||||||
|
.findFirst();
|
||||||
|
|
||||||
|
if (pbsSample.isEmpty() || registrySample.isEmpty()) {
|
||||||
|
final var uris = classes.stream()
|
||||||
|
.limit(20)
|
||||||
|
.map(javaClass -> javaClass.getName() + " -> " + PbsModuleOrigins.sourceUri(javaClass))
|
||||||
|
.toList();
|
||||||
|
fail("PBS/registry module origins were not visible to ArchUnit. sample URIs: " + uris);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(pbsSample.isPresent());
|
||||||
|
assertTrue(registrySample.isPresent());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package p.studio.architecture;
|
||||||
|
|
||||||
|
import com.tngtech.archunit.base.DescribedPredicate;
|
||||||
|
import com.tngtech.archunit.core.domain.JavaClass;
|
||||||
|
|
||||||
|
final class PbsModuleOrigins {
|
||||||
|
static final String PBS_GRADLE_PATH = ":prometeu-compiler:frontends:prometeu-frontend-pbs";
|
||||||
|
|
||||||
|
private PbsModuleOrigins() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean isPbsModule(final JavaClass javaClass) {
|
||||||
|
return uriContains(javaClass, "/prometeu-frontend-pbs/")
|
||||||
|
|| uriContains(javaClass, "prometeu-frontend-pbs.jar");
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean isRegistryModule(final JavaClass javaClass) {
|
||||||
|
return uriContains(javaClass, "/prometeu-frontend-registry/")
|
||||||
|
|| uriContains(javaClass, "prometeu-frontend-registry.jar");
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean isFrontendApiModule(final JavaClass javaClass) {
|
||||||
|
return uriContains(javaClass, "/prometeu-frontend-api/")
|
||||||
|
|| uriContains(javaClass, "prometeu-frontend-api.jar");
|
||||||
|
}
|
||||||
|
|
||||||
|
static DescribedPredicate<JavaClass> fromPbsModule() {
|
||||||
|
return DescribedPredicate.describe(
|
||||||
|
"originate from the PBS frontend module",
|
||||||
|
PbsModuleOrigins::isPbsModule);
|
||||||
|
}
|
||||||
|
|
||||||
|
static DescribedPredicate<JavaClass> fromRegistryModule() {
|
||||||
|
return DescribedPredicate.describe(
|
||||||
|
"originate from the frontend registry module",
|
||||||
|
PbsModuleOrigins::isRegistryModule);
|
||||||
|
}
|
||||||
|
|
||||||
|
static DescribedPredicate<JavaClass> fromFrontendApiModule() {
|
||||||
|
return DescribedPredicate.describe(
|
||||||
|
"originate from the frontend-api module",
|
||||||
|
PbsModuleOrigins::isFrontendApiModule);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String sourceUri(final JavaClass javaClass) {
|
||||||
|
return javaClass.getSource()
|
||||||
|
.map(source -> normalize(source.getUri().toString()))
|
||||||
|
.orElse("<no source>");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean uriContains(final JavaClass javaClass, final String fragment) {
|
||||||
|
return javaClass.getSource()
|
||||||
|
.map(source -> normalize(source.getUri().toString()).contains(fragment))
|
||||||
|
.orElse(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalize(final String uri) {
|
||||||
|
return uri.replace('\\', '/');
|
||||||
|
}
|
||||||
|
}
|
||||||
+888
@@ -0,0 +1,888 @@
|
|||||||
|
package p.studio.compiler;
|
||||||
|
|
||||||
|
import p.studio.compiler.messages.FESurfaceContext;
|
||||||
|
import p.studio.compiler.messages.BuildingIssueSink;
|
||||||
|
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.models.SourceKind;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsEditorialRename;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsEditorialWorkspaceSymbol;
|
||||||
|
import p.studio.compiler.pbs.PbsCallHierarchy;
|
||||||
|
import p.studio.compiler.pbs.PbsDocumentFormatter;
|
||||||
|
import p.studio.compiler.pbs.PbsSemanticTokenOverlay;
|
||||||
|
import p.studio.compiler.pbs.PbsStructureRanges;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsQuickFix;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsQuickFixCollector;
|
||||||
|
import p.studio.compiler.services.PBSFrontendPhaseService.PbsSemanticReadSurface;
|
||||||
|
import p.studio.compiler.services.FrontendCallHierarchyItem;
|
||||||
|
import p.studio.compiler.services.FrontendCallSite;
|
||||||
|
import p.studio.compiler.services.FrontendCodeAction;
|
||||||
|
import p.studio.compiler.services.FrontendCompletionCandidate;
|
||||||
|
import p.studio.compiler.services.FrontendSymbolKind;
|
||||||
|
import p.studio.compiler.services.FrontendDocumentLink;
|
||||||
|
import p.studio.compiler.services.FrontendFoldingRange;
|
||||||
|
import p.studio.compiler.services.FrontendSelectionRange;
|
||||||
|
import p.studio.compiler.services.FrontendDefinitionLocation;
|
||||||
|
import p.studio.compiler.services.FrontendDocumentRequest;
|
||||||
|
import p.studio.compiler.services.FrontendDocumentSymbol;
|
||||||
|
import p.studio.compiler.services.FrontendRenameEdit;
|
||||||
|
import p.studio.compiler.services.FrontendRenameResult;
|
||||||
|
import p.studio.compiler.services.FrontendDocumentation;
|
||||||
|
import p.studio.compiler.services.FrontendEditorialContext;
|
||||||
|
import p.studio.compiler.services.FrontendHover;
|
||||||
|
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;
|
||||||
|
import p.studio.compiler.source.identifiers.FileId;
|
||||||
|
import p.studio.compiler.source.tables.FileTableReader;
|
||||||
|
import p.studio.compiler.source.tables.ModuleReference;
|
||||||
|
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;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public final class PBSFrontendLanguageService implements FrontendLanguageService {
|
||||||
|
private final PbsEditorialSupportService editorialSupportService;
|
||||||
|
private final PBSSemanticTokenProvider semanticTokenProvider;
|
||||||
|
|
||||||
|
public PBSFrontendLanguageService() {
|
||||||
|
this(new PbsEditorialSupportService(), new PBSSemanticTokenProvider());
|
||||||
|
}
|
||||||
|
|
||||||
|
PBSFrontendLanguageService(
|
||||||
|
final PbsEditorialSupportService editorialSupportService,
|
||||||
|
final PBSSemanticTokenProvider semanticTokenProvider) {
|
||||||
|
this.editorialSupportService = Objects.requireNonNull(editorialSupportService, "editorialSupportService");
|
||||||
|
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,
|
||||||
|
final FileId fileId) {
|
||||||
|
if (phaseContext == null || fileId == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
final var semanticReadSurface = PBSFrontendPhaseService.semanticReadSurface(
|
||||||
|
phaseContext,
|
||||||
|
DiagnosticSink.empty(),
|
||||||
|
BuildingIssueSink.empty());
|
||||||
|
final var ast = semanticReadSurface.astByFile().get(fileId);
|
||||||
|
if (ast == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.of(new FrontendEditorialContext(
|
||||||
|
ast,
|
||||||
|
semanticReadSurface.supplementalTopDeclsByFile().getOrDefault(fileId, ReadOnlyList.empty()),
|
||||||
|
phaseContext.feSurfaceContext(),
|
||||||
|
phaseContext.fileTable,
|
||||||
|
semanticReadSurface));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<PbsEditorialCompletionCandidate> completion(
|
||||||
|
final String sourceText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final FESurfaceContext feSurfaceContext,
|
||||||
|
final int offset) {
|
||||||
|
return editorialSupportService.completion(sourceText, ast, supplementalTopDecls, feSurfaceContext, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendCompletionCandidate> completion(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|
||||||
|
|| !(editorialContext.supplementalDeclarations() instanceof ReadOnlyList<?> supplementalTopDecls)
|
||||||
|
|| !(editorialContext.semanticContext() instanceof FESurfaceContext feSurfaceContext)) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (insideModuleRef(ast, offset)
|
||||||
|
&& editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface) {
|
||||||
|
return moduleCompletions(surface.moduleCompletionLabels());
|
||||||
|
}
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
|
||||||
|
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
|
||||||
|
return completion(
|
||||||
|
request.documentText(),
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext,
|
||||||
|
offset).stream()
|
||||||
|
.map(this::toFrontendCompletionCandidate)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<PbsEditorialResolvedSymbol> hover(
|
||||||
|
final String sourceText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final FESurfaceContext feSurfaceContext,
|
||||||
|
final int offset) {
|
||||||
|
return editorialSupportService.hover(sourceText, ast, supplementalTopDecls, feSurfaceContext, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<FrontendHover> hover(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|
||||||
|
|| !(editorialContext.supplementalDeclarations() instanceof ReadOnlyList<?> supplementalTopDecls)
|
||||||
|
|| !(editorialContext.semanticContext() instanceof FESurfaceContext feSurfaceContext)) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
|
||||||
|
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
|
||||||
|
return hover(
|
||||||
|
request.documentText(),
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext,
|
||||||
|
offset).map(this::toFrontendHover);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<PbsEditorialSignatureHelp> signatureHelp(
|
||||||
|
final String sourceText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final FESurfaceContext feSurfaceContext,
|
||||||
|
final int offset) {
|
||||||
|
return editorialSupportService.signatureHelp(sourceText, ast, supplementalTopDecls, feSurfaceContext, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FrontendSignatureHelp signatureHelp(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|
||||||
|
|| !(editorialContext.supplementalDeclarations() instanceof ReadOnlyList<?> supplementalTopDecls)
|
||||||
|
|| !(editorialContext.semanticContext() instanceof FESurfaceContext feSurfaceContext)) {
|
||||||
|
return FrontendSignatureHelp.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
|
||||||
|
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
|
||||||
|
return signatureHelp(
|
||||||
|
request.documentText(),
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext,
|
||||||
|
offset)
|
||||||
|
.map(this::toFrontendSignatureHelp)
|
||||||
|
.orElseGet(FrontendSignatureHelp::empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<PbsEditorialLocation> definition(
|
||||||
|
final String sourceText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final FESurfaceContext feSurfaceContext,
|
||||||
|
final int offset) {
|
||||||
|
return editorialSupportService.definition(sourceText, ast, supplementalTopDecls, feSurfaceContext, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendDefinitionLocation> definition(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|
||||||
|
|| !(editorialContext.supplementalDeclarations() instanceof ReadOnlyList<?> supplementalTopDecls)
|
||||||
|
|| !(editorialContext.semanticContext() instanceof FESurfaceContext feSurfaceContext)
|
||||||
|
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
|
||||||
|
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
|
||||||
|
final ArrayList<FrontendDefinitionLocation> locations = new ArrayList<>();
|
||||||
|
for (final PbsEditorialLocation location : definition(
|
||||||
|
request.documentText(),
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext,
|
||||||
|
offset)) {
|
||||||
|
toFrontendLocation(location, fileTable).ifPresent(locations::add);
|
||||||
|
}
|
||||||
|
return List.copyOf(locations);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendDefinitionLocation> references(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|
||||||
|
|| !(editorialContext.supplementalDeclarations() instanceof ReadOnlyList<?> supplementalTopDecls)
|
||||||
|
|| !(editorialContext.semanticContext() instanceof FESurfaceContext feSurfaceContext)
|
||||||
|
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
|
||||||
|
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
|
||||||
|
final List<PbsEditorialLocation> editorialIdentity = definition(
|
||||||
|
request.documentText(),
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext,
|
||||||
|
offset);
|
||||||
|
final ArrayList<PbsEditorialLocation> physicalIdentity = new ArrayList<>();
|
||||||
|
for (final PbsEditorialLocation location : editorialIdentity) {
|
||||||
|
if (toFrontendLocation(location, fileTable).isPresent()) {
|
||||||
|
physicalIdentity.add(location);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (physicalIdentity.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
final EditorialDocument cursorDocument = new EditorialDocument(
|
||||||
|
request.documentText(),
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext);
|
||||||
|
final List<PbsEditorialLocation> usages = editorialSupportService.references(
|
||||||
|
cursorDocument,
|
||||||
|
offset,
|
||||||
|
projectDocuments(request, editorialContext, cursorDocument, fileTable));
|
||||||
|
final LinkedHashMap<String, FrontendDefinitionLocation> mapped = new LinkedHashMap<>();
|
||||||
|
for (final PbsEditorialLocation usage : usages) {
|
||||||
|
toFrontendLocation(usage, fileTable).ifPresent(location ->
|
||||||
|
mapped.putIfAbsent(frontendLocationKey(location), location));
|
||||||
|
}
|
||||||
|
return List.copyOf(mapped.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendDocumentSymbol> documentSymbols(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
if (editorialContext == null || !(editorialContext.syntaxTree() instanceof PbsAst.File ast)) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
return editorialSupportService.documentSymbols(ast).stream()
|
||||||
|
.map(this::toFrontendDocumentSymbol)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendWorkspaceSymbol> workspaceSymbols(
|
||||||
|
final FrontendWorkspaceRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)
|
||||||
|
|| !(editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface)
|
||||||
|
|| surface.astByFile() == null
|
||||||
|
|| surface.astByFile().isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<FrontendWorkspaceSymbol> symbols = new ArrayList<>();
|
||||||
|
for (final var entry : surface.astByFile().entrySet()) {
|
||||||
|
final Path path = pathForRegularSource(entry.getKey(), fileTable);
|
||||||
|
if (path == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final PbsAst.File fileAst = entry.getValue();
|
||||||
|
if (fileAst == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final PbsEditorialWorkspaceSymbol symbol : editorialSupportService.workspaceSymbols(
|
||||||
|
fileAst,
|
||||||
|
request.query())) {
|
||||||
|
toFrontendWorkspaceSymbol(symbol, path).ifPresent(symbols::add);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
symbols.sort(Comparator
|
||||||
|
.comparing(FrontendWorkspaceSymbol::name, String.CASE_INSENSITIVE_ORDER)
|
||||||
|
.thenComparing(symbol -> symbol.path().toString())
|
||||||
|
.thenComparingInt(FrontendWorkspaceSymbol::startOffset));
|
||||||
|
return List.copyOf(symbols);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<FrontendDefinitionLocation> prepareRename(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset) {
|
||||||
|
final PbsEditorialRename planned = editorialRename(request, editorialContext, offset, null);
|
||||||
|
if (planned == null || !planned.allowed()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
if (!(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
if (physicalIdentity(planned, fileTable).isEmpty()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return toFrontendLocation(planned.placeholder(), fileTable);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FrontendRenameResult rename(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset,
|
||||||
|
final String newName) {
|
||||||
|
if (newName == null) {
|
||||||
|
return FrontendRenameResult.refused("invalid identifier");
|
||||||
|
}
|
||||||
|
final PbsEditorialRename planned = editorialRename(request, editorialContext, offset, newName);
|
||||||
|
if (planned == null) {
|
||||||
|
return FrontendRenameResult.refused("not renameable");
|
||||||
|
}
|
||||||
|
if (!planned.allowed()) {
|
||||||
|
return FrontendRenameResult.refused(planned.refusal());
|
||||||
|
}
|
||||||
|
if (!(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
|
||||||
|
return FrontendRenameResult.refused("not renameable");
|
||||||
|
}
|
||||||
|
if (physicalIdentity(planned, fileTable).isEmpty()) {
|
||||||
|
return FrontendRenameResult.refused("not renameable");
|
||||||
|
}
|
||||||
|
final LinkedHashMap<String, FrontendRenameEdit> edits = new LinkedHashMap<>();
|
||||||
|
for (final PbsEditorialLocation site : planned.sites()) {
|
||||||
|
toFrontendLocation(site, fileTable).ifPresent(location ->
|
||||||
|
edits.putIfAbsent(
|
||||||
|
frontendLocationKey(location),
|
||||||
|
new FrontendRenameEdit(
|
||||||
|
location.path(),
|
||||||
|
location.startOffset(),
|
||||||
|
location.endOffset(),
|
||||||
|
newName)));
|
||||||
|
}
|
||||||
|
if (edits.isEmpty()) {
|
||||||
|
return FrontendRenameResult.refused("not renameable");
|
||||||
|
}
|
||||||
|
return FrontendRenameResult.applied(List.copyOf(edits.values()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean documentLinksSupported() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendDocumentLink> documentLinks(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|
||||||
|
|| !(editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface)
|
||||||
|
|| surface.physicalModuleFileByReference() == null
|
||||||
|
|| ast.imports() == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<FrontendDocumentLink> links = new ArrayList<>();
|
||||||
|
for (final PbsAst.ImportDecl importDecl : ast.imports()) {
|
||||||
|
if (importDecl == null || importDecl.moduleRef() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final PbsAst.ModuleRef moduleRef = importDecl.moduleRef();
|
||||||
|
final Span span = moduleRef.span();
|
||||||
|
if (span == null || span.isNone() || moduleRef.project() == null || moduleRef.project().isBlank()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final Path target = surface.physicalModuleFileByReference().get(
|
||||||
|
new ModuleReference(moduleRef.project(), moduleRef.pathSegments()));
|
||||||
|
if (target == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
links.add(new FrontendDocumentLink(
|
||||||
|
target,
|
||||||
|
toOffset(span.getStart()),
|
||||||
|
toOffset(span.getEnd())));
|
||||||
|
}
|
||||||
|
return List.copyOf(links);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean foldingRangesSupported() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendFoldingRange> foldingRanges(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
return PbsStructureRanges.foldingRanges(request == null || request.documentText() == null
|
||||||
|
? ""
|
||||||
|
: request.documentText());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean selectionRangesSupported() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendSelectionRange> selectionRanges(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final List<Integer> offsets) {
|
||||||
|
return PbsStructureRanges.selectionRanges(
|
||||||
|
request == null || request.documentText() == null ? "" : request.documentText(),
|
||||||
|
offsets);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean callHierarchySupported() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendCallHierarchyItem> prepareCallHierarchy(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset) {
|
||||||
|
final PbsAst.File ast = callHierarchyAst(editorialContext);
|
||||||
|
if (ast == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
return PbsCallHierarchy.prepare(ast, offset).stream().map(this::toCallItem).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendCallSite> incomingCalls(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final FrontendCallHierarchyItem target) {
|
||||||
|
return callSites(callHierarchyAst(editorialContext), target, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendCallSite> outgoingCalls(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final FrontendCallHierarchyItem target) {
|
||||||
|
return callSites(callHierarchyAst(editorialContext), target, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<FrontendCallSite> callSites(
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final FrontendCallHierarchyItem target,
|
||||||
|
final boolean incoming) {
|
||||||
|
if (ast == null || target == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final PbsCallHierarchy.Callable callable = new PbsCallHierarchy.Callable(
|
||||||
|
target.name(),
|
||||||
|
target.method(),
|
||||||
|
target.startOffset(),
|
||||||
|
target.endOffset());
|
||||||
|
final var calls = incoming
|
||||||
|
? PbsCallHierarchy.incomingCalls(ast, callable)
|
||||||
|
: PbsCallHierarchy.outgoingCalls(ast, callable);
|
||||||
|
return calls.stream()
|
||||||
|
.map(call -> new FrontendCallSite(
|
||||||
|
toCallItem(incoming ? call.caller() : call.callee()),
|
||||||
|
call.startOffset(),
|
||||||
|
call.endOffset()))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PbsAst.File callHierarchyAst(final FrontendEditorialContext editorialContext) {
|
||||||
|
if (editorialContext == null || !(editorialContext.syntaxTree() instanceof PbsAst.File ast)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return ast;
|
||||||
|
}
|
||||||
|
|
||||||
|
private FrontendCallHierarchyItem toCallItem(final PbsCallHierarchy.Callable callable) {
|
||||||
|
return new FrontendCallHierarchyItem(
|
||||||
|
callable.name(),
|
||||||
|
callable.method(),
|
||||||
|
callable.startOffset(),
|
||||||
|
callable.endOffset());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean formattingSupported() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<String> formatDocument(final FrontendDocumentRequest request) {
|
||||||
|
return Optional.of(PbsDocumentFormatter.format(
|
||||||
|
request == null || request.documentText() == null ? "" : request.documentText()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean codeActionsSupported() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendCodeAction> codeActions(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|
||||||
|
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final FileId fileId = ast.span() == null ? null : ast.span().getFileId();
|
||||||
|
final Path path = pathForRegularSource(fileId, fileTable);
|
||||||
|
if (path == null || !path.equals(request.documentPath().toAbsolutePath().normalize())) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final boolean interfaceModule = editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface
|
||||||
|
&& surface.sourceKindByFile() != null
|
||||||
|
&& surface.sourceKindByFile().get(fileId) == SourceKind.SDK_INTERFACE;
|
||||||
|
final ArrayList<FrontendCodeAction> actions = new ArrayList<>();
|
||||||
|
for (final PbsQuickFix repair : PbsQuickFixCollector.collect(ast, interfaceModule)) {
|
||||||
|
actions.add(new FrontendCodeAction(
|
||||||
|
repair.title(),
|
||||||
|
repair.diagnosticCode(),
|
||||||
|
path,
|
||||||
|
repair.startOffset(),
|
||||||
|
repair.endOffset(),
|
||||||
|
repair.newText()));
|
||||||
|
}
|
||||||
|
return List.copyOf(actions);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PbsEditorialRename editorialRename(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final int offset,
|
||||||
|
final String newName) {
|
||||||
|
if (request == null
|
||||||
|
|| editorialContext == null
|
||||||
|
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|
||||||
|
|| !(editorialContext.supplementalDeclarations() instanceof ReadOnlyList<?> supplementalTopDecls)
|
||||||
|
|| !(editorialContext.semanticContext() instanceof FESurfaceContext feSurfaceContext)
|
||||||
|
|| !(editorialContext.sourceFiles() instanceof FileTableReader fileTable)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
|
||||||
|
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
|
||||||
|
final EditorialDocument cursorDocument = new EditorialDocument(
|
||||||
|
request.documentText(),
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext);
|
||||||
|
return editorialSupportService.rename(
|
||||||
|
cursorDocument,
|
||||||
|
offset,
|
||||||
|
newName,
|
||||||
|
projectDocuments(request, editorialContext, cursorDocument, fileTable));
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<FrontendDefinitionLocation> physicalIdentity(
|
||||||
|
final PbsEditorialRename planned,
|
||||||
|
final FileTableReader fileTable) {
|
||||||
|
final ArrayList<FrontendDefinitionLocation> locations = new ArrayList<>();
|
||||||
|
for (final PbsEditorialLocation location : planned.identity()) {
|
||||||
|
toFrontendLocation(location, fileTable).ifPresent(locations::add);
|
||||||
|
}
|
||||||
|
return List.copyOf(locations);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendSemanticToken> semanticTokens(final FrontendDocumentRequest request) {
|
||||||
|
return semanticTokens(request, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FrontendSemanticToken> semanticTokens(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext) {
|
||||||
|
final String text = request == null || request.documentText() == null ? "" : request.documentText();
|
||||||
|
final List<FrontendSemanticToken> baseline = semanticTokenProvider.tokenize(text);
|
||||||
|
if (editorialContext == null
|
||||||
|
|| !(editorialContext.syntaxTree() instanceof PbsAst.File ast)
|
||||||
|
|| !(editorialContext.supplementalDeclarations() instanceof ReadOnlyList<?> supplementalTopDecls)
|
||||||
|
|| !(editorialContext.semanticContext() instanceof FESurfaceContext feSurfaceContext)) {
|
||||||
|
return baseline;
|
||||||
|
}
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> typedSupplementalTopDecls =
|
||||||
|
(ReadOnlyList<PbsAst.TopDecl>) supplementalTopDecls;
|
||||||
|
return PbsSemanticTokenOverlay.apply(
|
||||||
|
baseline,
|
||||||
|
text,
|
||||||
|
ast,
|
||||||
|
typedSupplementalTopDecls,
|
||||||
|
feSurfaceContext,
|
||||||
|
editorialSupportService);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<FrontendSemanticToken> semanticTokens(final String documentText) {
|
||||||
|
return semanticTokenProvider.tokenize(documentText == null ? "" : documentText);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean insideModuleRef(final PbsAst.File ast, final int offset) {
|
||||||
|
if (ast == null || ast.imports() == null || offset < 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (final PbsAst.ImportDecl importDecl : ast.imports()) {
|
||||||
|
if (importDecl == null || importDecl.moduleRef() == null || importDecl.moduleRef().span() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final long start = importDecl.moduleRef().span().getStart();
|
||||||
|
final long end = importDecl.moduleRef().span().getEnd();
|
||||||
|
if (end > start && start <= offset && offset <= end) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<FrontendCompletionCandidate> moduleCompletions(final List<String> labels) {
|
||||||
|
if (labels == null || labels.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<FrontendCompletionCandidate> candidates = new ArrayList<>();
|
||||||
|
for (final String label : labels) {
|
||||||
|
if (label == null || label.isBlank()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
candidates.add(new FrontendCompletionCandidate(
|
||||||
|
label,
|
||||||
|
FrontendSymbolKind.MODULE,
|
||||||
|
"module",
|
||||||
|
"",
|
||||||
|
""));
|
||||||
|
}
|
||||||
|
return List.copyOf(candidates);
|
||||||
|
}
|
||||||
|
|
||||||
|
private FrontendCompletionCandidate toFrontendCompletionCandidate(final PbsEditorialCompletionCandidate candidate) {
|
||||||
|
return new FrontendCompletionCandidate(
|
||||||
|
candidate.label(),
|
||||||
|
toFrontendSymbolKind(candidate.kind()),
|
||||||
|
candidate.detail(),
|
||||||
|
candidate.documentation(),
|
||||||
|
candidate.origin());
|
||||||
|
}
|
||||||
|
|
||||||
|
private FrontendHover toFrontendHover(final PbsEditorialResolvedSymbol symbol) {
|
||||||
|
return new FrontendHover(
|
||||||
|
symbol.displayName(),
|
||||||
|
toFrontendSymbolKind(symbol.kind()),
|
||||||
|
symbol.detail(),
|
||||||
|
symbol.origin(),
|
||||||
|
symbol.signatures().stream()
|
||||||
|
.map(this::toFrontendSignature)
|
||||||
|
.toList(),
|
||||||
|
FrontendDocumentation.markdown(symbol.documentation()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private FrontendSignatureHelp toFrontendSignatureHelp(final PbsEditorialSignatureHelp signatureHelp) {
|
||||||
|
return new FrontendSignatureHelp(
|
||||||
|
signatureHelp.signatures().stream()
|
||||||
|
.map(this::toFrontendSignature)
|
||||||
|
.toList(),
|
||||||
|
signatureHelp.activeSignature(),
|
||||||
|
signatureHelp.activeParameter());
|
||||||
|
}
|
||||||
|
|
||||||
|
private FrontendSignature toFrontendSignature(final p.studio.compiler.pbs.semantics.PbsEditorialSignature signature) {
|
||||||
|
return new FrontendSignature(signature.label(), signature.parameterLabels(), "");
|
||||||
|
}
|
||||||
|
|
||||||
|
private FrontendSymbolKind toFrontendSymbolKind(final PbsEditorialSymbolKind kind) {
|
||||||
|
return FrontendSymbolKind.valueOf(kind.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Optional<FrontendWorkspaceSymbol> toFrontendWorkspaceSymbol(
|
||||||
|
final PbsEditorialWorkspaceSymbol symbol,
|
||||||
|
final Path path) {
|
||||||
|
if (symbol == null || path == null || symbol.span() == null || symbol.span().isNone()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.of(new FrontendWorkspaceSymbol(
|
||||||
|
symbol.name(),
|
||||||
|
toFrontendSymbolKind(symbol.kind()),
|
||||||
|
symbol.detail(),
|
||||||
|
symbol.containerName(),
|
||||||
|
path,
|
||||||
|
toOffset(symbol.span().getStart()),
|
||||||
|
toOffset(symbol.span().getEnd())));
|
||||||
|
}
|
||||||
|
|
||||||
|
private FrontendDocumentSymbol toFrontendDocumentSymbol(final PbsEditorialDocumentSymbol symbol) {
|
||||||
|
final int start = toOffset(symbol.span().getStart());
|
||||||
|
final int end = toOffset(symbol.span().getEnd());
|
||||||
|
return new FrontendDocumentSymbol(
|
||||||
|
symbol.name(),
|
||||||
|
toFrontendSymbolKind(symbol.kind()),
|
||||||
|
symbol.detail(),
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
symbol.children().stream().map(this::toFrontendDocumentSymbol).toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<EditorialDocument> projectDocuments(
|
||||||
|
final FrontendDocumentRequest request,
|
||||||
|
final FrontendEditorialContext editorialContext,
|
||||||
|
final EditorialDocument cursorDocument,
|
||||||
|
final FileTableReader fileTable) {
|
||||||
|
if (!(editorialContext.projectSurface() instanceof PbsSemanticReadSurface surface)
|
||||||
|
|| surface.astByFile() == null
|
||||||
|
|| surface.astByFile().isEmpty()) {
|
||||||
|
return List.of(cursorDocument);
|
||||||
|
}
|
||||||
|
final ArrayList<EditorialDocument> documents = new ArrayList<>();
|
||||||
|
for (final var entry : surface.astByFile().entrySet()) {
|
||||||
|
if (!isRegularSource(entry.getKey(), fileTable)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final PbsAst.File fileAst = entry.getValue();
|
||||||
|
if (fileAst == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> fileSupplementals = fileAst == cursorDocument.ast()
|
||||||
|
? cursorDocument.supplementalTopDecls()
|
||||||
|
: surface.supplementalTopDeclsByFile().getOrDefault(entry.getKey(), ReadOnlyList.empty());
|
||||||
|
documents.add(new EditorialDocument(
|
||||||
|
textForFile(entry.getKey(), fileTable, request),
|
||||||
|
fileAst,
|
||||||
|
fileSupplementals,
|
||||||
|
cursorDocument.feSurfaceContext()));
|
||||||
|
}
|
||||||
|
if (documents.isEmpty()) {
|
||||||
|
return List.of(cursorDocument);
|
||||||
|
}
|
||||||
|
return List.copyOf(documents);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path pathForRegularSource(
|
||||||
|
final FileId fileId,
|
||||||
|
final FileTableReader fileTable) {
|
||||||
|
if (!isRegularSource(fileId, fileTable)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return fileTable.get(fileId).getCanonPath().toAbsolutePath().normalize();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isRegularSource(
|
||||||
|
final FileId fileId,
|
||||||
|
final FileTableReader fileTable) {
|
||||||
|
if (fileId == null || fileId.isNone() || fileTable == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
final var sourceHandle = fileTable.get(fileId);
|
||||||
|
if (sourceHandle == null || sourceHandle.getCanonPath() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return Files.isRegularFile(sourceHandle.getCanonPath().toAbsolutePath().normalize());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String textForFile(
|
||||||
|
final FileId fileId,
|
||||||
|
final FileTableReader fileTable,
|
||||||
|
final FrontendDocumentRequest request) {
|
||||||
|
final var sourceHandle = fileTable.get(fileId);
|
||||||
|
if (sourceHandle == null || sourceHandle.getCanonPath() == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
final Path path = sourceHandle.getCanonPath().toAbsolutePath().normalize();
|
||||||
|
if (request != null
|
||||||
|
&& request.documentPath() != null
|
||||||
|
&& path.equals(request.documentPath().toAbsolutePath().normalize())) {
|
||||||
|
return request.documentText() == null ? "" : request.documentText();
|
||||||
|
}
|
||||||
|
return sourceHandle.readUtf8().orElse("");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String frontendLocationKey(final FrontendDefinitionLocation location) {
|
||||||
|
return location.path() + ":" + location.startOffset() + ":" + location.endOffset();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Optional<FrontendDefinitionLocation> toFrontendLocation(
|
||||||
|
final PbsEditorialLocation location,
|
||||||
|
final FileTableReader fileTable) {
|
||||||
|
if (location == null || fileTable == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
final Span span = location.span();
|
||||||
|
if (span == null || span.isNone() || span.getFileId() == null || span.getFileId().isNone()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
final var sourceHandle = fileTable.get(span.getFileId());
|
||||||
|
if (sourceHandle == null || sourceHandle.getCanonPath() == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
final Path path = sourceHandle.getCanonPath().toAbsolutePath().normalize();
|
||||||
|
if (!Files.isRegularFile(path)) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.of(new FrontendDefinitionLocation(
|
||||||
|
path,
|
||||||
|
toOffset(span.getStart()),
|
||||||
|
toOffset(span.getEnd())));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int toOffset(final long value) {
|
||||||
|
if (value <= 0L) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return (int) Math.min(Integer.MAX_VALUE, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
+44
@@ -0,0 +1,44 @@
|
|||||||
|
package p.studio.compiler;
|
||||||
|
|
||||||
|
import p.studio.compiler.models.FrontendSpec;
|
||||||
|
import p.studio.compiler.services.FrontendLanguageService;
|
||||||
|
import p.studio.compiler.services.FrontendPhaseService;
|
||||||
|
import p.studio.compiler.services.FrontendProvider;
|
||||||
|
import p.studio.compiler.services.PBSFrontendPhaseService;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public final class PBSFrontendProvider implements FrontendProvider {
|
||||||
|
private final FrontendPhaseService compiler;
|
||||||
|
private final PBSFrontendLanguageService languageService;
|
||||||
|
|
||||||
|
public PBSFrontendProvider() {
|
||||||
|
this(new PBSFrontendPhaseService(), new PBSFrontendLanguageService());
|
||||||
|
}
|
||||||
|
|
||||||
|
PBSFrontendProvider(final FrontendPhaseService compiler) {
|
||||||
|
this(compiler, new PBSFrontendLanguageService());
|
||||||
|
}
|
||||||
|
|
||||||
|
PBSFrontendProvider(
|
||||||
|
final FrontendPhaseService compiler,
|
||||||
|
final PBSFrontendLanguageService languageService) {
|
||||||
|
this.compiler = compiler;
|
||||||
|
this.languageService = languageService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FrontendSpec specification() {
|
||||||
|
return PBSDefinitions.PBS;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FrontendPhaseService compiler() {
|
||||||
|
return compiler;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<FrontendLanguageService> languageService() {
|
||||||
|
return Optional.of(languageService);
|
||||||
|
}
|
||||||
|
}
|
||||||
+335
@@ -0,0 +1,335 @@
|
|||||||
|
package p.studio.compiler.pbs;
|
||||||
|
|
||||||
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class PbsCallHierarchy {
|
||||||
|
private PbsCallHierarchy() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Callable(
|
||||||
|
String name,
|
||||||
|
boolean method,
|
||||||
|
int startOffset,
|
||||||
|
int endOffset) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record CallSite(
|
||||||
|
Callable caller,
|
||||||
|
Callable callee,
|
||||||
|
int startOffset,
|
||||||
|
int endOffset) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Callable> prepare(final PbsAst.File ast, final int offset) {
|
||||||
|
Callable best = null;
|
||||||
|
for (final Callable callable : callables(ast)) {
|
||||||
|
if (callable.startOffset() > offset || offset >= callable.endOffset()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (best == null || callable.endOffset() - callable.startOffset() < best.endOffset() - best.startOffset()) {
|
||||||
|
best = callable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best == null ? List.of() : List.of(best);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<CallSite> incomingCalls(final PbsAst.File ast, final Callable target) {
|
||||||
|
if (target == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<CallSite> calls = new ArrayList<>();
|
||||||
|
for (final CallSite call : calls(ast)) {
|
||||||
|
if (sameCallable(call.callee(), target)) {
|
||||||
|
calls.add(call);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return List.copyOf(calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<CallSite> outgoingCalls(final PbsAst.File ast, final Callable target) {
|
||||||
|
if (target == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<CallSite> calls = new ArrayList<>();
|
||||||
|
for (final CallSite call : calls(ast)) {
|
||||||
|
if (sameCallable(call.caller(), target)) {
|
||||||
|
calls.add(call);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return List.copyOf(calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean sameCallable(final Callable left, final Callable right) {
|
||||||
|
return left != null
|
||||||
|
&& right != null
|
||||||
|
&& left.method() == right.method()
|
||||||
|
&& left.name().equals(right.name())
|
||||||
|
&& left.startOffset() == right.startOffset()
|
||||||
|
&& left.endOffset() == right.endOffset();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Callable> callables(final PbsAst.File ast) {
|
||||||
|
final ArrayList<Callable> callables = new ArrayList<>();
|
||||||
|
if (ast == null || ast.topDecls() == null) {
|
||||||
|
return callables;
|
||||||
|
}
|
||||||
|
for (final PbsAst.TopDecl topDecl : ast.topDecls()) {
|
||||||
|
collectCallables(topDecl, callables);
|
||||||
|
}
|
||||||
|
return callables;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void collectCallables(final PbsAst.TopDecl topDecl, final List<Callable> callables) {
|
||||||
|
switch (topDecl) {
|
||||||
|
case null -> {
|
||||||
|
}
|
||||||
|
case PbsAst.FunctionDecl functionDecl -> callables.add(callable(functionDecl.name(), false, functionDecl.span()));
|
||||||
|
case PbsAst.StructDecl structDecl -> {
|
||||||
|
if (structDecl.methods() != null) {
|
||||||
|
for (final PbsAst.FunctionDecl method : structDecl.methods()) {
|
||||||
|
if (method != null) {
|
||||||
|
callables.add(callable(method.name(), true, method.span()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (structDecl.ctors() != null) {
|
||||||
|
for (final PbsAst.CtorDecl ctor : structDecl.ctors()) {
|
||||||
|
if (ctor != null) {
|
||||||
|
callables.add(callable(ctor.name(), true, ctor.span()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.ServiceDecl serviceDecl -> {
|
||||||
|
if (serviceDecl.methods() != null) {
|
||||||
|
for (final PbsAst.FunctionDecl method : serviceDecl.methods()) {
|
||||||
|
if (method != null) {
|
||||||
|
callables.add(callable(method.name(), true, method.span()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<CallSite> calls(final PbsAst.File ast) {
|
||||||
|
final List<Callable> callables = callables(ast);
|
||||||
|
final ArrayList<CallSite> calls = new ArrayList<>();
|
||||||
|
for (final Callable caller : callables) {
|
||||||
|
final PbsAst.Block body = body(ast, caller);
|
||||||
|
if (body == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final ArrayList<PbsAst.CallExpr> found = new ArrayList<>();
|
||||||
|
collectCalls(body, found);
|
||||||
|
for (final PbsAst.CallExpr call : found) {
|
||||||
|
final Callable callee = resolveCallee(call, callables);
|
||||||
|
final int[] span = offsets(call.span());
|
||||||
|
if (callee == null || span == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
calls.add(new CallSite(caller, callee, span[0], span[1]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return calls;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Callable resolveCallee(final PbsAst.CallExpr call, final List<Callable> callables) {
|
||||||
|
if (call == null || call.callee() == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final boolean method = call.callee() instanceof PbsAst.MemberExpr;
|
||||||
|
final String name = switch (call.callee()) {
|
||||||
|
case PbsAst.IdentifierExpr identifier -> identifier.name();
|
||||||
|
case PbsAst.MemberExpr member -> member.memberName();
|
||||||
|
default -> null;
|
||||||
|
};
|
||||||
|
if (name == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (final Callable callable : callables) {
|
||||||
|
if (callable.method() == method && callable.name().equals(name)) {
|
||||||
|
return callable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PbsAst.Block body(final PbsAst.File ast, final Callable caller) {
|
||||||
|
for (final Callable callable : callables(ast)) {
|
||||||
|
if (!sameCallable(callable, caller)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return findBody(ast, caller);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PbsAst.Block findBody(final PbsAst.File ast, final Callable caller) {
|
||||||
|
if (ast.topDecls() == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (final PbsAst.TopDecl topDecl : ast.topDecls()) {
|
||||||
|
final PbsAst.Block body = findBody(topDecl, caller);
|
||||||
|
if (body != null) {
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PbsAst.Block findBody(final PbsAst.TopDecl topDecl, final Callable caller) {
|
||||||
|
switch (topDecl) {
|
||||||
|
case null -> {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
case PbsAst.FunctionDecl functionDecl -> {
|
||||||
|
if (matches(functionDecl.name(), false, functionDecl.span(), caller)) {
|
||||||
|
return functionDecl.body();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
case PbsAst.StructDecl structDecl -> {
|
||||||
|
if (structDecl.methods() != null) {
|
||||||
|
for (final PbsAst.FunctionDecl method : structDecl.methods()) {
|
||||||
|
if (method != null && matches(method.name(), true, method.span(), caller)) {
|
||||||
|
return method.body();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (structDecl.ctors() != null) {
|
||||||
|
for (final PbsAst.CtorDecl ctor : structDecl.ctors()) {
|
||||||
|
if (ctor != null && matches(ctor.name(), true, ctor.span(), caller)) {
|
||||||
|
return ctor.body();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
case PbsAst.ServiceDecl serviceDecl -> {
|
||||||
|
if (serviceDecl.methods() == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (final PbsAst.FunctionDecl method : serviceDecl.methods()) {
|
||||||
|
if (method != null && matches(method.name(), true, method.span(), caller)) {
|
||||||
|
return method.body();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void collectCalls(final PbsAst.Block block, final List<PbsAst.CallExpr> calls) {
|
||||||
|
if (block == null || block.statements() == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (final PbsAst.Statement statement : block.statements()) {
|
||||||
|
collectCalls(statement, calls);
|
||||||
|
}
|
||||||
|
collectCalls(block.tailExpression(), calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void collectCalls(final PbsAst.Statement statement, final List<PbsAst.CallExpr> calls) {
|
||||||
|
switch (statement) {
|
||||||
|
case null -> {
|
||||||
|
}
|
||||||
|
case PbsAst.LetStatement letStatement -> collectCalls(letStatement.initializer(), calls);
|
||||||
|
case PbsAst.ReturnStatement returnStatement -> collectCalls(returnStatement.value(), calls);
|
||||||
|
case PbsAst.AssignStatement assignStatement -> collectCalls(assignStatement.value(), calls);
|
||||||
|
case PbsAst.ExpressionStatement expressionStatement -> collectCalls(expressionStatement.expression(), calls);
|
||||||
|
case PbsAst.IfStatement ifStatement -> {
|
||||||
|
collectCalls(ifStatement.condition(), calls);
|
||||||
|
collectCalls(ifStatement.thenBlock(), calls);
|
||||||
|
collectCalls(ifStatement.elseBlock(), calls);
|
||||||
|
collectCalls(ifStatement.elseIf(), calls);
|
||||||
|
}
|
||||||
|
case PbsAst.ForStatement forStatement -> {
|
||||||
|
collectCalls(forStatement.fromExpression(), calls);
|
||||||
|
collectCalls(forStatement.untilExpression(), calls);
|
||||||
|
collectCalls(forStatement.stepExpression(), calls);
|
||||||
|
collectCalls(forStatement.body(), calls);
|
||||||
|
}
|
||||||
|
case PbsAst.WhileStatement whileStatement -> {
|
||||||
|
collectCalls(whileStatement.condition(), calls);
|
||||||
|
collectCalls(whileStatement.body(), calls);
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void collectCalls(final PbsAst.Expression expression, final List<PbsAst.CallExpr> calls) {
|
||||||
|
switch (expression) {
|
||||||
|
case null -> {
|
||||||
|
}
|
||||||
|
case PbsAst.CallExpr callExpr -> {
|
||||||
|
calls.add(callExpr);
|
||||||
|
collectCalls(callExpr.callee(), calls);
|
||||||
|
if (callExpr.arguments() != null) {
|
||||||
|
for (final PbsAst.Expression argument : callExpr.arguments()) {
|
||||||
|
collectCalls(argument, calls);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.MemberExpr memberExpr -> collectCalls(memberExpr.receiver(), calls);
|
||||||
|
case PbsAst.BinaryExpr binaryExpr -> {
|
||||||
|
collectCalls(binaryExpr.left(), calls);
|
||||||
|
collectCalls(binaryExpr.right(), calls);
|
||||||
|
}
|
||||||
|
case PbsAst.UnaryExpr unaryExpr -> collectCalls(unaryExpr.expression(), calls);
|
||||||
|
case PbsAst.GroupExpr groupExpr -> collectCalls(groupExpr.expression(), calls);
|
||||||
|
case PbsAst.IfExpr ifExpr -> {
|
||||||
|
collectCalls(ifExpr.condition(), calls);
|
||||||
|
collectCalls(ifExpr.thenBlock(), calls);
|
||||||
|
collectCalls(ifExpr.elseExpression(), calls);
|
||||||
|
}
|
||||||
|
case PbsAst.BlockExpr blockExpr -> collectCalls(blockExpr.block(), calls);
|
||||||
|
case PbsAst.ApplyExpr applyExpr -> {
|
||||||
|
collectCalls(applyExpr.callee(), calls);
|
||||||
|
collectCalls(applyExpr.argument(), calls);
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean matches(
|
||||||
|
final String name,
|
||||||
|
final boolean method,
|
||||||
|
final Span span,
|
||||||
|
final Callable caller) {
|
||||||
|
final Callable callable = callable(name, method, span);
|
||||||
|
return callable != null && sameCallable(callable, caller);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Callable callable(final String name, final boolean method, final Span span) {
|
||||||
|
final int[] offsets = offsets(span);
|
||||||
|
if (name == null || name.isBlank() || offsets == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return new Callable(name, method, offsets[0], offsets[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[] offsets(final Span span) {
|
||||||
|
if (span == null || span.getEnd() <= span.getStart()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return new int[] {toOffset(span.getStart()), toOffset(span.getEnd())};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int toOffset(final long value) {
|
||||||
|
if (value <= 0L) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return (int) Math.min(Integer.MAX_VALUE, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
+179
@@ -0,0 +1,179 @@
|
|||||||
|
package p.studio.compiler.pbs;
|
||||||
|
|
||||||
|
import p.studio.compiler.pbs.lexer.PbsLexer;
|
||||||
|
import p.studio.compiler.pbs.lexer.PbsToken;
|
||||||
|
import p.studio.compiler.pbs.lexer.PbsTokenKind;
|
||||||
|
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||||
|
import p.studio.compiler.source.identifiers.FileId;
|
||||||
|
import p.studio.utilities.structures.ReadOnlyList;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
public final class PbsDocumentFormatter {
|
||||||
|
private static final int INDENT_SPACES = 4;
|
||||||
|
|
||||||
|
private PbsDocumentFormatter() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String format(final String documentText) {
|
||||||
|
final String text = documentText == null ? "" : documentText;
|
||||||
|
if (text.isEmpty()) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
final ReadOnlyList<PbsToken> tokens = PbsLexer.lex(text, FileId.none(), DiagnosticSink.empty());
|
||||||
|
final ArrayList<SourceLine> lines = splitLines(text);
|
||||||
|
final StringBuilder formatted = new StringBuilder(text.length());
|
||||||
|
int depth = 0;
|
||||||
|
for (final SourceLine line : lines) {
|
||||||
|
if (isDocInterior(line, tokens)) {
|
||||||
|
formatted.append(line.content()).append(line.ending());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final int leadingClosers = leadingClosers(line, tokens);
|
||||||
|
final int indent = Math.max(0, depth - leadingClosers);
|
||||||
|
formatted.append(reindent(line.content(), indent)).append(line.ending());
|
||||||
|
depth = depthAfter(line, tokens, depth);
|
||||||
|
}
|
||||||
|
return formatted.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isDocInterior(final SourceLine line, final ReadOnlyList<PbsToken> tokens) {
|
||||||
|
for (final PbsToken token : tokens) {
|
||||||
|
if (token.kind() != PbsTokenKind.DOC_TEXT_BLOCK) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (line.startByte() > token.start() && line.endByte() <= token.end()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int leadingClosers(final SourceLine line, final ReadOnlyList<PbsToken> tokens) {
|
||||||
|
int closers = 0;
|
||||||
|
boolean seenCode = false;
|
||||||
|
for (final PbsToken token : tokens) {
|
||||||
|
if (token.start() < line.startByte() || token.start() >= line.endByte()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.kind() == PbsTokenKind.COMMENT) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!seenCode && isCloser(token.kind())) {
|
||||||
|
closers += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seenCode = true;
|
||||||
|
}
|
||||||
|
return closers;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int depthAfter(
|
||||||
|
final SourceLine line,
|
||||||
|
final ReadOnlyList<PbsToken> tokens,
|
||||||
|
final int depth) {
|
||||||
|
int next = depth;
|
||||||
|
for (final PbsToken token : tokens) {
|
||||||
|
if (token.start() < line.startByte() || token.start() >= line.endByte()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isOpener(token.kind())) {
|
||||||
|
next += 1;
|
||||||
|
} else if (isCloser(token.kind())) {
|
||||||
|
next = Math.max(0, next - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isOpener(final PbsTokenKind kind) {
|
||||||
|
return kind == PbsTokenKind.LEFT_BRACE || kind == PbsTokenKind.LEFT_PAREN;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isCloser(final PbsTokenKind kind) {
|
||||||
|
return kind == PbsTokenKind.RIGHT_BRACE || kind == PbsTokenKind.RIGHT_PAREN;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String reindent(final String content, final int indent) {
|
||||||
|
int index = 0;
|
||||||
|
while (index < content.length()) {
|
||||||
|
final char character = content.charAt(index);
|
||||||
|
if (character != ' ' && character != '\t') {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
if (index == content.length()) {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
return " ".repeat(indent * INDENT_SPACES) + content.substring(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ArrayList<SourceLine> splitLines(final String text) {
|
||||||
|
final ArrayList<SourceLine> lines = new ArrayList<>();
|
||||||
|
final byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
|
||||||
|
int charIndex = 0;
|
||||||
|
int byteIndex = 0;
|
||||||
|
int lineCharStart = 0;
|
||||||
|
int lineByteStart = 0;
|
||||||
|
while (charIndex < text.length()) {
|
||||||
|
final int codePoint = text.codePointAt(charIndex);
|
||||||
|
final int charWidth = Character.charCount(codePoint);
|
||||||
|
final int byteWidth = utf8Length(codePoint);
|
||||||
|
if (codePoint == '\n') {
|
||||||
|
lines.add(new SourceLine(
|
||||||
|
text.substring(lineCharStart, charIndex),
|
||||||
|
"\n",
|
||||||
|
lineByteStart,
|
||||||
|
byteIndex));
|
||||||
|
charIndex += charWidth;
|
||||||
|
byteIndex += byteWidth;
|
||||||
|
lineCharStart = charIndex;
|
||||||
|
lineByteStart = byteIndex;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (codePoint == '\r' && charIndex + charWidth < text.length() && text.codePointAt(charIndex + charWidth) == '\n') {
|
||||||
|
lines.add(new SourceLine(
|
||||||
|
text.substring(lineCharStart, charIndex),
|
||||||
|
"\r\n",
|
||||||
|
lineByteStart,
|
||||||
|
byteIndex));
|
||||||
|
charIndex += charWidth + 1;
|
||||||
|
byteIndex += byteWidth + 1;
|
||||||
|
lineCharStart = charIndex;
|
||||||
|
lineByteStart = byteIndex;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
charIndex += charWidth;
|
||||||
|
byteIndex += byteWidth;
|
||||||
|
}
|
||||||
|
if (lineCharStart < text.length()) {
|
||||||
|
lines.add(new SourceLine(
|
||||||
|
text.substring(lineCharStart),
|
||||||
|
"",
|
||||||
|
lineByteStart,
|
||||||
|
bytes.length));
|
||||||
|
}
|
||||||
|
if (lines.isEmpty()) {
|
||||||
|
lines.add(new SourceLine(text, "", 0, bytes.length));
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int utf8Length(final int codePoint) {
|
||||||
|
if (codePoint <= 0x7F) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (codePoint <= 0x7FF) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
if (codePoint <= 0xFFFF) {
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
return 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
private record SourceLine(String content, String ending, int startByte, int endByte) {
|
||||||
|
}
|
||||||
|
}
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
package p.studio.compiler.pbs;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class PbsDocumentationTextBlockNormalizer {
|
||||||
|
private static final String DELIMITER = "\"\"\"";
|
||||||
|
|
||||||
|
private PbsDocumentationTextBlockNormalizer() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String normalizeLexeme(final String lexeme) {
|
||||||
|
if (lexeme == null || !lexeme.startsWith(DELIMITER) || !lexeme.endsWith(DELIMITER) || lexeme.length() < 6) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return normalizeContent(lexeme.substring(DELIMITER.length(), lexeme.length() - DELIMITER.length()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String normalizeContent(final String rawContent) {
|
||||||
|
final var lines = splitLines(rawContent == null ? "" : rawContent.replace("\r\n", "\n").replace('\r', '\n'));
|
||||||
|
removeIncidentalBoundaryLines(lines);
|
||||||
|
final int commonIndent = commonIndent(lines);
|
||||||
|
if (commonIndent > 0) {
|
||||||
|
for (int i = 0; i < lines.size(); i++) {
|
||||||
|
final var line = lines.get(i);
|
||||||
|
if (line.isBlank()) {
|
||||||
|
lines.set(i, "");
|
||||||
|
} else {
|
||||||
|
lines.set(i, line.substring(Math.min(commonIndent, leadingWhitespace(line))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return String.join("\n", lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> splitLines(final String text) {
|
||||||
|
final var lines = new ArrayList<String>();
|
||||||
|
final var parts = text.split("\n", -1);
|
||||||
|
for (final var part : parts) {
|
||||||
|
lines.add(part);
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void removeIncidentalBoundaryLines(final List<String> lines) {
|
||||||
|
if (!lines.isEmpty() && lines.getFirst().isBlank()) {
|
||||||
|
lines.removeFirst();
|
||||||
|
}
|
||||||
|
if (!lines.isEmpty() && lines.getLast().isBlank()) {
|
||||||
|
lines.removeLast();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int commonIndent(final List<String> lines) {
|
||||||
|
var common = Integer.MAX_VALUE;
|
||||||
|
for (final var line : lines) {
|
||||||
|
if (line.isBlank()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
common = Math.min(common, leadingWhitespace(line));
|
||||||
|
}
|
||||||
|
return common == Integer.MAX_VALUE ? 0 : common;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int leadingWhitespace(final String line) {
|
||||||
|
var count = 0;
|
||||||
|
while (count < line.length() && Character.isWhitespace(line.charAt(count))) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
}
|
||||||
+76
-47
@@ -8,6 +8,9 @@ import p.studio.compiler.models.IRFunction;
|
|||||||
import p.studio.compiler.models.IRGlobal;
|
import p.studio.compiler.models.IRGlobal;
|
||||||
import p.studio.compiler.models.IRGlobalOrigin;
|
import p.studio.compiler.models.IRGlobalOrigin;
|
||||||
import p.studio.compiler.models.IRGlobalVisibility;
|
import p.studio.compiler.models.IRGlobalVisibility;
|
||||||
|
import p.studio.compiler.models.IRLifecycleCallableReference;
|
||||||
|
import p.studio.compiler.models.IRLifecycleCallableRole;
|
||||||
|
import p.studio.compiler.models.IRLifecycleFileDeclaration;
|
||||||
import p.studio.compiler.models.IRReservedMetadata;
|
import p.studio.compiler.models.IRReservedMetadata;
|
||||||
import p.studio.compiler.models.IRSyntheticCallableKind;
|
import p.studio.compiler.models.IRSyntheticCallableKind;
|
||||||
import p.studio.compiler.models.IRSyntheticFunction;
|
import p.studio.compiler.models.IRSyntheticFunction;
|
||||||
@@ -215,6 +218,12 @@ public final class PbsFrontendCompiler {
|
|||||||
if (fileInitExecutable != null) {
|
if (fileInitExecutable != null) {
|
||||||
executableFunctions.add(fileInitExecutable);
|
executableFunctions.add(fileInitExecutable);
|
||||||
}
|
}
|
||||||
|
final var lifecycleDeclaration = lowerLifecycleDeclaration(
|
||||||
|
fileId,
|
||||||
|
effectiveModuleId,
|
||||||
|
lifecycleArtifacts,
|
||||||
|
fileInitExecutable,
|
||||||
|
executableFunctions);
|
||||||
return new IRBackendFile(
|
return new IRBackendFile(
|
||||||
fileId,
|
fileId,
|
||||||
functions,
|
functions,
|
||||||
@@ -224,7 +233,8 @@ public final class PbsFrontendCompiler {
|
|||||||
reservedMetadata,
|
reservedMetadata,
|
||||||
effectiveModulePool,
|
effectiveModulePool,
|
||||||
ReadOnlyList.wrap(callableSignatures),
|
ReadOnlyList.wrap(callableSignatures),
|
||||||
executableLowering.intrinsicPool());
|
executableLowering.intrinsicPool(),
|
||||||
|
lifecycleDeclaration);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String callableShapeSurfaceOf(final PbsAst.FunctionDecl functionDecl) {
|
public String callableShapeSurfaceOf(final PbsAst.FunctionDecl functionDecl) {
|
||||||
@@ -306,33 +316,19 @@ public final class PbsFrontendCompiler {
|
|||||||
final var frameDecl = lifecycleArtifacts.frameDecl();
|
final var frameDecl = lifecycleArtifacts.frameDecl();
|
||||||
final var firstGlobalDecl = lifecycleArtifacts.firstGlobalDecl();
|
final var firstGlobalDecl = lifecycleArtifacts.firstGlobalDecl();
|
||||||
|
|
||||||
final var fileInitAnchorSpan = initDecl != null ? initDecl.span() : firstGlobalDecl == null ? null : firstGlobalDecl.span();
|
final var ordinaryFileInit = frameDecl == null ? initDecl : null;
|
||||||
final var fileInitAnchorName = initDecl != null ? initDecl.name() : firstGlobalDecl == null ? "" : firstGlobalDecl.name();
|
final var fileInitAnchorSpan = ordinaryFileInit != null
|
||||||
|
? ordinaryFileInit.span()
|
||||||
|
: firstGlobalDecl == null ? null : firstGlobalDecl.span();
|
||||||
|
final var fileInitAnchorName = ordinaryFileInit != null
|
||||||
|
? ordinaryFileInit.name()
|
||||||
|
: firstGlobalDecl == null ? "" : firstGlobalDecl.name();
|
||||||
if (fileInitAnchorSpan != null) {
|
if (fileInitAnchorSpan != null) {
|
||||||
syntheticFunctions.add(new IRSyntheticFunction(
|
syntheticFunctions.add(new IRSyntheticFunction(
|
||||||
moduleId,
|
moduleId,
|
||||||
fileInitCallableName(fileId),
|
fileInitCallableName(fileId),
|
||||||
IRSyntheticCallableKind.FILE_INIT_FRAGMENT,
|
IRSyntheticCallableKind.FILE_INIT_FRAGMENT,
|
||||||
new IRSyntheticOrigin(fileId, fileInitAnchorName, fileInitAnchorSpan)));
|
new IRSyntheticOrigin(fileId, fileInitAnchorName, fileInitAnchorSpan)));
|
||||||
syntheticFunctions.add(new IRSyntheticFunction(
|
|
||||||
moduleId,
|
|
||||||
moduleInitCallableName(moduleId),
|
|
||||||
IRSyntheticCallableKind.MODULE_INIT,
|
|
||||||
new IRSyntheticOrigin(fileId, fileInitAnchorName, fileInitAnchorSpan)));
|
|
||||||
}
|
|
||||||
if (initDecl != null && frameDecl != null) {
|
|
||||||
syntheticFunctions.add(new IRSyntheticFunction(
|
|
||||||
moduleId,
|
|
||||||
projectInitCallableName(moduleId),
|
|
||||||
IRSyntheticCallableKind.PROJECT_INIT,
|
|
||||||
new IRSyntheticOrigin(fileId, initDecl.name(), initDecl.span())));
|
|
||||||
}
|
|
||||||
if (frameDecl != null) {
|
|
||||||
syntheticFunctions.add(new IRSyntheticFunction(
|
|
||||||
moduleId,
|
|
||||||
frameWrapperCallableName(moduleId),
|
|
||||||
IRSyntheticCallableKind.PUBLISHED_FRAME_WRAPPER,
|
|
||||||
new IRSyntheticOrigin(fileId, frameDecl.name(), frameDecl.span())));
|
|
||||||
}
|
}
|
||||||
return ReadOnlyList.wrap(syntheticFunctions);
|
return ReadOnlyList.wrap(syntheticFunctions);
|
||||||
}
|
}
|
||||||
@@ -343,8 +339,10 @@ public final class PbsFrontendCompiler {
|
|||||||
final PbsLifecycleArtifacts lifecycleArtifacts,
|
final PbsLifecycleArtifacts lifecycleArtifacts,
|
||||||
final ArrayList<IRBackendExecutableFunction> executableFunctions,
|
final ArrayList<IRBackendExecutableFunction> executableFunctions,
|
||||||
final ArrayList<CallableSignatureRef> callableSignatures) {
|
final ArrayList<CallableSignatureRef> callableSignatures) {
|
||||||
if (lifecycleArtifacts.firstGlobalDecl() == null
|
final var ordinaryFileInit = lifecycleArtifacts.frameDecl() == null
|
||||||
&& lifecycleArtifacts.initDecl() == null) {
|
? lifecycleArtifacts.initDecl()
|
||||||
|
: null;
|
||||||
|
if (lifecycleArtifacts.firstGlobalDecl() == null && ordinaryFileInit == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
final var syntheticCallableName = fileInitCallableName(fileId);
|
final var syntheticCallableName = fileInitCallableName(fileId);
|
||||||
@@ -352,8 +350,8 @@ public final class PbsFrontendCompiler {
|
|||||||
callableSignatures.add(new CallableSignatureRef(moduleId, syntheticCallableName, 0, "() -> unit"));
|
callableSignatures.add(new CallableSignatureRef(moduleId, syntheticCallableName, 0, "() -> unit"));
|
||||||
|
|
||||||
final var instructions = new ArrayList<IRBackendExecutableFunction.Instruction>();
|
final var instructions = new ArrayList<IRBackendExecutableFunction.Instruction>();
|
||||||
final var moduleInitSource = lifecycleArtifacts.initDecl();
|
final var moduleInitSource = ordinaryFileInit;
|
||||||
if (moduleInitSource != null && moduleInitSource != lifecycleArtifacts.frameDecl()) {
|
if (moduleInitSource != null) {
|
||||||
final var initExecutable = resolveLifecycleExecutable(executableFunctions, moduleId, moduleInitSource.name());
|
final var initExecutable = resolveLifecycleExecutable(executableFunctions, moduleId, moduleInitSource.name());
|
||||||
if (initExecutable != null) {
|
if (initExecutable != null) {
|
||||||
instructions.add(new IRBackendExecutableFunction.Instruction(
|
instructions.add(new IRBackendExecutableFunction.Instruction(
|
||||||
@@ -390,6 +388,58 @@ public final class PbsFrontendCompiler {
|
|||||||
span);
|
span);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private IRLifecycleFileDeclaration lowerLifecycleDeclaration(
|
||||||
|
final FileId fileId,
|
||||||
|
final ModuleId moduleId,
|
||||||
|
final PbsLifecycleArtifacts lifecycleArtifacts,
|
||||||
|
final IRBackendExecutableFunction fileInitExecutable,
|
||||||
|
final ArrayList<IRBackendExecutableFunction> executableFunctions) {
|
||||||
|
final var fileInitReference = fileInitExecutable == null
|
||||||
|
? null
|
||||||
|
: new IRLifecycleCallableReference(
|
||||||
|
moduleId,
|
||||||
|
fileId,
|
||||||
|
fileInitExecutable.callableId(),
|
||||||
|
IRLifecycleCallableRole.FILE_INIT_FRAGMENT,
|
||||||
|
fileInitExecutable.span());
|
||||||
|
|
||||||
|
final var projectInitSource = lifecycleArtifacts.frameDecl() == null
|
||||||
|
? null
|
||||||
|
: lifecycleArtifacts.initDecl();
|
||||||
|
final var projectInitExecutable = projectInitSource == null
|
||||||
|
? null
|
||||||
|
: resolveLifecycleExecutable(executableFunctions, moduleId, projectInitSource.name());
|
||||||
|
final var projectInitReference = projectInitExecutable == null
|
||||||
|
? null
|
||||||
|
: new IRLifecycleCallableReference(
|
||||||
|
moduleId,
|
||||||
|
fileId,
|
||||||
|
projectInitExecutable.callableId(),
|
||||||
|
IRLifecycleCallableRole.PROJECT_INIT,
|
||||||
|
projectInitSource.span());
|
||||||
|
|
||||||
|
final var frameSource = lifecycleArtifacts.frameDecl();
|
||||||
|
final var frameExecutable = frameSource == null
|
||||||
|
? null
|
||||||
|
: resolveLifecycleExecutable(executableFunctions, moduleId, frameSource.name());
|
||||||
|
final var frameReference = frameExecutable == null
|
||||||
|
? null
|
||||||
|
: new IRLifecycleCallableReference(
|
||||||
|
moduleId,
|
||||||
|
fileId,
|
||||||
|
frameExecutable.callableId(),
|
||||||
|
IRLifecycleCallableRole.FRAME_ROOT,
|
||||||
|
frameSource.span());
|
||||||
|
|
||||||
|
final var declaration = new IRLifecycleFileDeclaration(
|
||||||
|
moduleId,
|
||||||
|
fileId,
|
||||||
|
fileInitReference,
|
||||||
|
projectInitReference,
|
||||||
|
frameReference);
|
||||||
|
return declaration.isEmpty() ? null : declaration;
|
||||||
|
}
|
||||||
|
|
||||||
private IRBackendExecutableFunction resolveLifecycleExecutable(
|
private IRBackendExecutableFunction resolveLifecycleExecutable(
|
||||||
final ArrayList<IRBackendExecutableFunction> executableFunctions,
|
final ArrayList<IRBackendExecutableFunction> executableFunctions,
|
||||||
final ModuleId moduleId,
|
final ModuleId moduleId,
|
||||||
@@ -443,27 +493,6 @@ public final class PbsFrontendCompiler {
|
|||||||
return "__pbs.file_init$f" + fileId.getId();
|
return "__pbs.file_init$f" + fileId.getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String moduleInitCallableName(final ModuleId moduleId) {
|
|
||||||
return "__pbs.module_init$m" + normalizedModuleIndex(moduleId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String projectInitCallableName(final ModuleId moduleId) {
|
|
||||||
return "__pbs.project_init$m" + normalizedModuleIndex(moduleId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String frameWrapperCallableName(final ModuleId moduleId) {
|
|
||||||
return "__pbs.frame_wrapper$m" + normalizedModuleIndex(moduleId);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String bootGuardGlobalName(final ModuleId moduleId) {
|
|
||||||
return "__pbs.boot_guard$m" + normalizedModuleIndex(moduleId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int normalizedModuleIndex(final ModuleId moduleId) {
|
|
||||||
final var normalized = moduleId == null ? ModuleId.none() : moduleId;
|
|
||||||
return normalized.isNone() ? -1 : normalized.getIndex();
|
|
||||||
}
|
|
||||||
|
|
||||||
private int safeToInt(final long value) {
|
private int safeToInt(final long value) {
|
||||||
if (value > Integer.MAX_VALUE) {
|
if (value > Integer.MAX_VALUE) {
|
||||||
return Integer.MAX_VALUE;
|
return Integer.MAX_VALUE;
|
||||||
|
|||||||
+1
-1
@@ -50,7 +50,7 @@ public enum PbsSemanticKind {
|
|||||||
public static PbsSemanticKind forToken(final PbsToken token) {
|
public static PbsSemanticKind forToken(final PbsToken token) {
|
||||||
return switch (token.kind()) {
|
return switch (token.kind()) {
|
||||||
case COMMENT -> COMMENT;
|
case COMMENT -> COMMENT;
|
||||||
case STRING_LITERAL -> STRING;
|
case STRING_LITERAL, DOC_TEXT_BLOCK -> STRING;
|
||||||
case INT_LITERAL, FLOAT_LITERAL, BOUNDED_LITERAL -> NUMBER;
|
case INT_LITERAL, FLOAT_LITERAL, BOUNDED_LITERAL -> NUMBER;
|
||||||
case TRUE, FALSE, NONE, SOME, OK, ERR -> LITERAL;
|
case TRUE, FALSE, NONE, SOME, OK, ERR -> LITERAL;
|
||||||
case VOID, OPTIONAL, RESULT -> BUILTIN_TYPE;
|
case VOID, OPTIONAL, RESULT -> BUILTIN_TYPE;
|
||||||
|
|||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
package p.studio.compiler.pbs;
|
||||||
|
|
||||||
|
import p.studio.compiler.messages.FESurfaceContext;
|
||||||
|
import p.studio.compiler.models.FrontendSemanticToken;
|
||||||
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsEditorialResolvedSymbol;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsEditorialSupportService;
|
||||||
|
import p.studio.compiler.pbs.semantics.PbsEditorialSymbolKind;
|
||||||
|
import p.studio.utilities.structures.ReadOnlyList;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public final class PbsSemanticTokenOverlay {
|
||||||
|
private static final Set<String> LEXICAL_KEYS = Set.of(
|
||||||
|
PbsSemanticKind.COMMENT.semanticKey(),
|
||||||
|
PbsSemanticKind.STRING.semanticKey(),
|
||||||
|
PbsSemanticKind.NUMBER.semanticKey(),
|
||||||
|
PbsSemanticKind.LITERAL.semanticKey(),
|
||||||
|
PbsSemanticKind.KEYWORD.semanticKey(),
|
||||||
|
PbsSemanticKind.OPERATOR.semanticKey(),
|
||||||
|
PbsSemanticKind.PUNCTUATION.semanticKey());
|
||||||
|
|
||||||
|
private PbsSemanticTokenOverlay() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<FrontendSemanticToken> apply(
|
||||||
|
final List<FrontendSemanticToken> baseline,
|
||||||
|
final String documentText,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementalTopDecls,
|
||||||
|
final FESurfaceContext feSurfaceContext,
|
||||||
|
final PbsEditorialSupportService editorialSupportService) {
|
||||||
|
if (baseline == null || baseline.isEmpty() || ast == null || editorialSupportService == null) {
|
||||||
|
return baseline == null ? List.of() : List.copyOf(baseline);
|
||||||
|
}
|
||||||
|
final String text = documentText == null ? "" : documentText;
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementals = supplementalTopDecls == null
|
||||||
|
? ReadOnlyList.empty()
|
||||||
|
: supplementalTopDecls;
|
||||||
|
final FESurfaceContext surface = feSurfaceContext == null ? FESurfaceContext.empty() : feSurfaceContext;
|
||||||
|
final ArrayList<FrontendSemanticToken> overlaid = new ArrayList<>(baseline.size());
|
||||||
|
for (final FrontendSemanticToken token : baseline) {
|
||||||
|
overlaid.add(overlay(token, text, ast, supplementals, surface, editorialSupportService));
|
||||||
|
}
|
||||||
|
return List.copyOf(overlaid);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FrontendSemanticToken overlay(
|
||||||
|
final FrontendSemanticToken token,
|
||||||
|
final String text,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsAst.TopDecl> supplementals,
|
||||||
|
final FESurfaceContext surface,
|
||||||
|
final PbsEditorialSupportService editorialSupportService) {
|
||||||
|
if (token == null || LEXICAL_KEYS.contains(token.semanticKey())) {
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final String resolvedKey = editorialSupportService.hover(
|
||||||
|
text,
|
||||||
|
ast,
|
||||||
|
supplementals,
|
||||||
|
surface,
|
||||||
|
token.startOffset())
|
||||||
|
.map(PbsSemanticTokenOverlay::semanticKey)
|
||||||
|
.orElse(null);
|
||||||
|
if (resolvedKey == null || resolvedKey.equals(token.semanticKey())) {
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
return new FrontendSemanticToken(token.startOffset(), token.endOffset(), resolvedKey);
|
||||||
|
} catch (final RuntimeException ignored) {
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String semanticKey(final PbsEditorialResolvedSymbol symbol) {
|
||||||
|
if (symbol == null || symbol.kind() == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final PbsSemanticKind kind = switch (symbol.kind()) {
|
||||||
|
case FUNCTION -> PbsSemanticKind.FUNCTION;
|
||||||
|
case METHOD -> PbsSemanticKind.METHOD;
|
||||||
|
case CONSTRUCTOR -> PbsSemanticKind.CONSTRUCTOR;
|
||||||
|
case STRUCT -> PbsSemanticKind.STRUCT;
|
||||||
|
case BUILTIN_TYPE -> PbsSemanticKind.BUILTIN_TYPE;
|
||||||
|
case SERVICE -> PbsSemanticKind.SERVICE;
|
||||||
|
case HOST -> PbsSemanticKind.HOST;
|
||||||
|
case CONTRACT -> PbsSemanticKind.CONTRACT;
|
||||||
|
case CALLBACK -> PbsSemanticKind.CALLBACK;
|
||||||
|
case ENUM -> PbsSemanticKind.ENUM;
|
||||||
|
case ERROR -> PbsSemanticKind.ERROR;
|
||||||
|
case GLOBAL -> PbsSemanticKind.GLOBAL;
|
||||||
|
case CONST -> PbsSemanticKind.CONST;
|
||||||
|
case KEYWORD, LOCAL, PARAMETER, FIELD -> null;
|
||||||
|
};
|
||||||
|
return kind == null ? null : kind.semanticKey();
|
||||||
|
}
|
||||||
|
}
|
||||||
+380
@@ -0,0 +1,380 @@
|
|||||||
|
package p.studio.compiler.pbs;
|
||||||
|
|
||||||
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
|
import p.studio.compiler.pbs.lexer.PbsLexer;
|
||||||
|
import p.studio.compiler.pbs.lexer.PbsToken;
|
||||||
|
import p.studio.compiler.pbs.lexer.PbsTokenKind;
|
||||||
|
import p.studio.compiler.pbs.parser.PbsParser;
|
||||||
|
import p.studio.compiler.services.FrontendFoldingRange;
|
||||||
|
import p.studio.compiler.services.FrontendSelectionRange;
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||||
|
import p.studio.compiler.source.identifiers.FileId;
|
||||||
|
import p.studio.utilities.structures.ReadOnlyList;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class PbsStructureRanges {
|
||||||
|
private PbsStructureRanges() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<FrontendFoldingRange> foldingRanges(final String documentText) {
|
||||||
|
final String text = documentText == null ? "" : documentText;
|
||||||
|
final ReadOnlyList<PbsToken> tokens = PbsLexer.lex(text, FileId.none(), DiagnosticSink.empty());
|
||||||
|
final PbsAst.File ast = PbsParser.parse(tokens, FileId.none(), DiagnosticSink.empty());
|
||||||
|
return foldingRanges(text, ast, tokens);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<FrontendSelectionRange> selectionRanges(
|
||||||
|
final String documentText,
|
||||||
|
final List<Integer> offsets) {
|
||||||
|
final String text = documentText == null ? "" : documentText;
|
||||||
|
final ReadOnlyList<PbsToken> tokens = PbsLexer.lex(text, FileId.none(), DiagnosticSink.empty());
|
||||||
|
final PbsAst.File ast = PbsParser.parse(tokens, FileId.none(), DiagnosticSink.empty());
|
||||||
|
if (offsets == null || offsets.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final Collected collected = collect(ast);
|
||||||
|
final List<SpanPair> delimiters = delimiters(tokens, textEnd(text));
|
||||||
|
final ArrayList<FrontendSelectionRange> ranges = new ArrayList<>();
|
||||||
|
for (final Integer offset : offsets) {
|
||||||
|
if (offset == null || offset < 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final FrontendSelectionRange range = selectionAt(offset, tokens, collected, delimiters);
|
||||||
|
if (range != null) {
|
||||||
|
ranges.add(range);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return List.copyOf(ranges);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<FrontendFoldingRange> foldingRanges(
|
||||||
|
final String text,
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final ReadOnlyList<PbsToken> tokens) {
|
||||||
|
final Collected collected = collect(ast);
|
||||||
|
final LinkedHashSet<String> emitted = new LinkedHashSet<>();
|
||||||
|
final ArrayList<SpanPair> ranges = new ArrayList<>();
|
||||||
|
for (final SpanPair span : collected.folding()) {
|
||||||
|
addRange(ranges, emitted, span);
|
||||||
|
}
|
||||||
|
for (final SpanPair delimiter : delimiters(tokens, textEnd(text))) {
|
||||||
|
if (collected.coveredKeys().contains(delimiter.key())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
addRange(ranges, emitted, delimiter);
|
||||||
|
}
|
||||||
|
ranges.sort(Comparator.comparingInt(SpanPair::start).thenComparingInt(SpanPair::end));
|
||||||
|
return ranges.stream()
|
||||||
|
.map(span -> new FrontendFoldingRange(span.start(), span.end()))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FrontendSelectionRange selectionAt(
|
||||||
|
final int offset,
|
||||||
|
final ReadOnlyList<PbsToken> tokens,
|
||||||
|
final Collected collected,
|
||||||
|
final List<SpanPair> delimiters) {
|
||||||
|
final SpanPair identifier = smallest(identifierSpans(tokens), offset);
|
||||||
|
final SpanPair parameters = smallest(delimiters, offset);
|
||||||
|
final SpanPair block = smallest(collected.blocks(), offset);
|
||||||
|
final SpanPair declaration = smallest(collected.declarations(), offset);
|
||||||
|
FrontendSelectionRange node = null;
|
||||||
|
SpanPair previous = null;
|
||||||
|
for (final SpanPair layer : new SpanPair[] {declaration, block, parameters, identifier}) {
|
||||||
|
if (layer == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (previous != null && previous.start() == layer.start() && previous.end() == layer.end()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
node = new FrontendSelectionRange(layer.start(), layer.end(), node);
|
||||||
|
previous = layer;
|
||||||
|
}
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Collected collect(final PbsAst.File ast) {
|
||||||
|
final Collected collected = new Collected();
|
||||||
|
if (ast == null || ast.topDecls() == null) {
|
||||||
|
return collected;
|
||||||
|
}
|
||||||
|
for (final PbsAst.TopDecl topDecl : ast.topDecls()) {
|
||||||
|
visitTop(topDecl, true, collected);
|
||||||
|
}
|
||||||
|
return collected;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void visitTop(
|
||||||
|
final PbsAst.TopDecl topDecl,
|
||||||
|
final boolean topLevel,
|
||||||
|
final Collected collected) {
|
||||||
|
if (topDecl == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (topLevel && isListedDeclaration(topDecl)) {
|
||||||
|
addSpan(collected.folding(), topDecl.span());
|
||||||
|
}
|
||||||
|
if (isListedDeclaration(topDecl) || topDecl instanceof PbsAst.FunctionDecl) {
|
||||||
|
addSpan(collected.declarations(), topDecl.span());
|
||||||
|
}
|
||||||
|
switch (topDecl) {
|
||||||
|
case PbsAst.FunctionDecl functionDecl -> visitFunction(functionDecl, collected);
|
||||||
|
case PbsAst.StructDecl structDecl -> {
|
||||||
|
visitAttributes(structDecl.attributes(), collected);
|
||||||
|
if (structDecl.methods() != null) {
|
||||||
|
for (final PbsAst.FunctionDecl method : structDecl.methods()) {
|
||||||
|
visitTop(method, false, collected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (structDecl.ctors() != null) {
|
||||||
|
for (final PbsAst.CtorDecl ctor : structDecl.ctors()) {
|
||||||
|
visitCtor(ctor, collected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.ServiceDecl serviceDecl -> {
|
||||||
|
visitAttributes(serviceDecl.attributes(), collected);
|
||||||
|
if (serviceDecl.methods() != null) {
|
||||||
|
for (final PbsAst.FunctionDecl method : serviceDecl.methods()) {
|
||||||
|
visitTop(method, false, collected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.ContractDecl contractDecl -> visitAttributes(contractDecl.attributes(), collected);
|
||||||
|
case PbsAst.HostDecl hostDecl -> visitAttributes(hostDecl.attributes(), collected);
|
||||||
|
case PbsAst.EnumDecl enumDecl -> visitAttributes(enumDecl.attributes(), collected);
|
||||||
|
case PbsAst.ErrorDecl errorDecl -> visitAttributes(errorDecl.attributes(), collected);
|
||||||
|
case PbsAst.CallbackDecl callbackDecl -> visitAttributes(callbackDecl.attributes(), collected);
|
||||||
|
default -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void visitFunction(
|
||||||
|
final PbsAst.FunctionDecl functionDecl,
|
||||||
|
final Collected collected) {
|
||||||
|
visitAttributes(functionDecl.attributes(), collected);
|
||||||
|
coverBlock(functionDecl.body(), true, collected);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void visitCtor(
|
||||||
|
final PbsAst.CtorDecl ctor,
|
||||||
|
final Collected collected) {
|
||||||
|
if (ctor == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
addSpan(collected.declarations(), ctor.span());
|
||||||
|
coverBlock(ctor.body(), true, collected);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void visitAttributes(
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
|
final Collected collected) {
|
||||||
|
if (attributes == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (final PbsAst.Attribute attribute : attributes) {
|
||||||
|
if (attribute == null || attribute.arguments() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (final PbsAst.AttributeArgument argument : attribute.arguments()) {
|
||||||
|
if (argument != null && argument.value() instanceof PbsAst.AttributeDocTextBlockValue doc) {
|
||||||
|
addSpan(collected.folding(), doc.span());
|
||||||
|
addSpan(collected.blocks(), doc.span());
|
||||||
|
collected.cover(doc.span());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void coverBlock(
|
||||||
|
final PbsAst.Block block,
|
||||||
|
final boolean emit,
|
||||||
|
final Collected collected) {
|
||||||
|
if (block == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (emit) {
|
||||||
|
addSpan(collected.folding(), block.span());
|
||||||
|
}
|
||||||
|
addSpan(collected.blocks(), block.span());
|
||||||
|
collected.cover(block.span());
|
||||||
|
if (block.statements() == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (final PbsAst.Statement statement : block.statements()) {
|
||||||
|
coverStatement(statement, collected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void coverStatement(
|
||||||
|
final PbsAst.Statement statement,
|
||||||
|
final Collected collected) {
|
||||||
|
switch (statement) {
|
||||||
|
case null -> {
|
||||||
|
}
|
||||||
|
case PbsAst.IfStatement ifStatement -> {
|
||||||
|
coverBlock(ifStatement.thenBlock(), false, collected);
|
||||||
|
coverBlock(ifStatement.elseBlock(), false, collected);
|
||||||
|
coverStatement(ifStatement.elseIf(), collected);
|
||||||
|
}
|
||||||
|
case PbsAst.ForStatement forStatement -> coverBlock(forStatement.body(), false, collected);
|
||||||
|
case PbsAst.WhileStatement whileStatement -> coverBlock(whileStatement.body(), false, collected);
|
||||||
|
default -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isListedDeclaration(final PbsAst.TopDecl topDecl) {
|
||||||
|
return topDecl instanceof PbsAst.FunctionDecl
|
||||||
|
|| topDecl instanceof PbsAst.StructDecl
|
||||||
|
|| topDecl instanceof PbsAst.ServiceDecl
|
||||||
|
|| topDecl instanceof PbsAst.ContractDecl
|
||||||
|
|| topDecl instanceof PbsAst.HostDecl
|
||||||
|
|| topDecl instanceof PbsAst.EnumDecl
|
||||||
|
|| topDecl instanceof PbsAst.ErrorDecl
|
||||||
|
|| topDecl instanceof PbsAst.CallbackDecl;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<SpanPair> delimiters(
|
||||||
|
final ReadOnlyList<PbsToken> tokens,
|
||||||
|
final int textEnd) {
|
||||||
|
final ArrayList<PbsToken> stack = new ArrayList<>();
|
||||||
|
final ArrayList<SpanPair> pairs = new ArrayList<>();
|
||||||
|
if (tokens == null) {
|
||||||
|
return pairs;
|
||||||
|
}
|
||||||
|
for (final PbsToken token : tokens) {
|
||||||
|
if (token == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.kind() == PbsTokenKind.LEFT_BRACE || token.kind() == PbsTokenKind.LEFT_PAREN) {
|
||||||
|
stack.add(token);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.kind() == PbsTokenKind.DOC_TEXT_BLOCK) {
|
||||||
|
addPair(pairs, token.start(), token.end());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (token.kind() == PbsTokenKind.RIGHT_BRACE || token.kind() == PbsTokenKind.RIGHT_PAREN) {
|
||||||
|
final PbsTokenKind openKind = token.kind() == PbsTokenKind.RIGHT_BRACE
|
||||||
|
? PbsTokenKind.LEFT_BRACE
|
||||||
|
: PbsTokenKind.LEFT_PAREN;
|
||||||
|
if (!stack.isEmpty() && stack.getLast().kind() == openKind) {
|
||||||
|
final PbsToken open = stack.removeLast();
|
||||||
|
addPair(pairs, open.start(), token.end());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (final PbsToken open : stack) {
|
||||||
|
addPair(pairs, open.start(), textEnd);
|
||||||
|
}
|
||||||
|
return pairs;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<SpanPair> identifierSpans(final ReadOnlyList<PbsToken> tokens) {
|
||||||
|
final ArrayList<SpanPair> spans = new ArrayList<>();
|
||||||
|
if (tokens == null) {
|
||||||
|
return spans;
|
||||||
|
}
|
||||||
|
for (final PbsToken token : tokens) {
|
||||||
|
if (token != null && token.kind() == PbsTokenKind.IDENTIFIER) {
|
||||||
|
addPair(spans, token.start(), token.end());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return spans;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SpanPair smallest(final List<SpanPair> spans, final int offset) {
|
||||||
|
SpanPair best = null;
|
||||||
|
for (final SpanPair span : spans) {
|
||||||
|
if (span.start() > offset || offset >= span.end()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (best == null
|
||||||
|
|| span.end() - span.start() < best.end() - best.start()
|
||||||
|
|| (span.end() - span.start() == best.end() - best.start() && span.start() > best.start())) {
|
||||||
|
best = span;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addSpan(final List<SpanPair> spans, final Span span) {
|
||||||
|
if (span == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
addPair(spans, toOffset(span.getStart()), toOffset(span.getEnd()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addPair(final List<SpanPair> spans, final int start, final int end) {
|
||||||
|
if (start < 0 || end <= start) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
spans.add(new SpanPair(start, end));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addRange(
|
||||||
|
final List<SpanPair> ranges,
|
||||||
|
final LinkedHashSet<String> emitted,
|
||||||
|
final SpanPair span) {
|
||||||
|
if (span == null || !emitted.add(span.key())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ranges.add(span);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int textEnd(final String text) {
|
||||||
|
return text.getBytes(StandardCharsets.UTF_8).length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int toOffset(final long value) {
|
||||||
|
if (value <= 0L) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return (int) Math.min(Integer.MAX_VALUE, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private record SpanPair(int start, int end) {
|
||||||
|
private String key() {
|
||||||
|
return start + ":" + end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Collected {
|
||||||
|
private final ArrayList<SpanPair> folding = new ArrayList<>();
|
||||||
|
private final ArrayList<SpanPair> covered = new ArrayList<>();
|
||||||
|
private final ArrayList<SpanPair> blocks = new ArrayList<>();
|
||||||
|
private final ArrayList<SpanPair> declarations = new ArrayList<>();
|
||||||
|
|
||||||
|
private List<SpanPair> folding() {
|
||||||
|
return folding;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cover(final Span span) {
|
||||||
|
addSpan(covered, span);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LinkedHashSet<String> coveredKeys() {
|
||||||
|
final LinkedHashSet<String> keys = new LinkedHashSet<>();
|
||||||
|
for (final SpanPair span : covered) {
|
||||||
|
keys.add(span.key());
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<SpanPair> blocks() {
|
||||||
|
return blocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<SpanPair> declarations() {
|
||||||
|
return declarations;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
@@ -78,6 +78,7 @@ public final class PbsAst {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public sealed interface AttributeValue permits AttributeStringValue,
|
public sealed interface AttributeValue permits AttributeStringValue,
|
||||||
|
AttributeDocTextBlockValue,
|
||||||
AttributeIntValue,
|
AttributeIntValue,
|
||||||
AttributeBoolValue,
|
AttributeBoolValue,
|
||||||
AttributeErrorValue {
|
AttributeErrorValue {
|
||||||
@@ -89,6 +90,11 @@ public final class PbsAst {
|
|||||||
Span span) implements AttributeValue {
|
Span span) implements AttributeValue {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public record AttributeDocTextBlockValue(
|
||||||
|
String value,
|
||||||
|
Span span) implements AttributeValue {
|
||||||
|
}
|
||||||
|
|
||||||
public record AttributeIntValue(
|
public record AttributeIntValue(
|
||||||
long value,
|
long value,
|
||||||
Span span) implements AttributeValue {
|
Span span) implements AttributeValue {
|
||||||
@@ -132,6 +138,7 @@ public final class PbsAst {
|
|||||||
ReturnKind returnKind,
|
ReturnKind returnKind,
|
||||||
TypeRef returnType,
|
TypeRef returnType,
|
||||||
TypeRef resultErrorType,
|
TypeRef resultErrorType,
|
||||||
|
ReadOnlyList<Attribute> attributes,
|
||||||
LifecycleMarker lifecycleMarker,
|
LifecycleMarker lifecycleMarker,
|
||||||
Block body,
|
Block body,
|
||||||
Span span) implements TopDecl {
|
Span span) implements TopDecl {
|
||||||
@@ -143,18 +150,21 @@ public final class PbsAst {
|
|||||||
ReadOnlyList<FunctionDecl> methods,
|
ReadOnlyList<FunctionDecl> methods,
|
||||||
ReadOnlyList<CtorDecl> ctors,
|
ReadOnlyList<CtorDecl> ctors,
|
||||||
boolean hasBody,
|
boolean hasBody,
|
||||||
|
ReadOnlyList<Attribute> attributes,
|
||||||
Span span) implements TopDecl {
|
Span span) implements TopDecl {
|
||||||
}
|
}
|
||||||
|
|
||||||
public record ContractDecl(
|
public record ContractDecl(
|
||||||
String name,
|
String name,
|
||||||
ReadOnlyList<FunctionSignature> signatures,
|
ReadOnlyList<FunctionSignature> signatures,
|
||||||
|
ReadOnlyList<Attribute> attributes,
|
||||||
Span span) implements TopDecl {
|
Span span) implements TopDecl {
|
||||||
}
|
}
|
||||||
|
|
||||||
public record HostDecl(
|
public record HostDecl(
|
||||||
String name,
|
String name,
|
||||||
ReadOnlyList<FunctionSignature> signatures,
|
ReadOnlyList<FunctionSignature> signatures,
|
||||||
|
ReadOnlyList<Attribute> attributes,
|
||||||
Span span) implements TopDecl {
|
Span span) implements TopDecl {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,18 +179,21 @@ public final class PbsAst {
|
|||||||
public record ServiceDecl(
|
public record ServiceDecl(
|
||||||
String name,
|
String name,
|
||||||
ReadOnlyList<FunctionDecl> methods,
|
ReadOnlyList<FunctionDecl> methods,
|
||||||
|
ReadOnlyList<Attribute> attributes,
|
||||||
Span span) implements TopDecl {
|
Span span) implements TopDecl {
|
||||||
}
|
}
|
||||||
|
|
||||||
public record ErrorDecl(
|
public record ErrorDecl(
|
||||||
String name,
|
String name,
|
||||||
ReadOnlyList<String> cases,
|
ReadOnlyList<String> cases,
|
||||||
|
ReadOnlyList<Attribute> attributes,
|
||||||
Span span) implements TopDecl {
|
Span span) implements TopDecl {
|
||||||
}
|
}
|
||||||
|
|
||||||
public record EnumDecl(
|
public record EnumDecl(
|
||||||
String name,
|
String name,
|
||||||
ReadOnlyList<EnumCase> cases,
|
ReadOnlyList<EnumCase> cases,
|
||||||
|
ReadOnlyList<Attribute> attributes,
|
||||||
Span span) implements TopDecl {
|
Span span) implements TopDecl {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,6 +203,7 @@ public final class PbsAst {
|
|||||||
ReturnKind returnKind,
|
ReturnKind returnKind,
|
||||||
TypeRef returnType,
|
TypeRef returnType,
|
||||||
TypeRef resultErrorType,
|
TypeRef resultErrorType,
|
||||||
|
ReadOnlyList<Attribute> attributes,
|
||||||
Span span) implements TopDecl {
|
Span span) implements TopDecl {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
@@ -3,5 +3,6 @@ package p.studio.compiler.pbs.lexer;
|
|||||||
public enum LexErrors {
|
public enum LexErrors {
|
||||||
E_LEX_INVALID_CHAR,
|
E_LEX_INVALID_CHAR,
|
||||||
E_LEX_UNTERMINATED_STRING,
|
E_LEX_UNTERMINATED_STRING,
|
||||||
|
E_LEX_UNTERMINATED_DOC_TEXT_BLOCK,
|
||||||
E_LEX_INVALID_STRING_ESCAPE,
|
E_LEX_INVALID_STRING_ESCAPE,
|
||||||
}
|
}
|
||||||
|
|||||||
+65
-1
@@ -17,6 +17,7 @@ public final class PbsLexer {
|
|||||||
IDENTIFIER,
|
IDENTIFIER,
|
||||||
NUMBER,
|
NUMBER,
|
||||||
STRING,
|
STRING,
|
||||||
|
DOC_TEXT_BLOCK,
|
||||||
LINE_COMMENT
|
LINE_COMMENT
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,6 +46,32 @@ public final class PbsLexer {
|
|||||||
return lexer.lexInternal();
|
return lexer.lexInternal();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static boolean isKeyword(final String text) {
|
||||||
|
return text != null && KEYWORDS.containsKey(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isIdentifierLexeme(final String text) {
|
||||||
|
if (text == null || text.isEmpty() || isKeyword(text)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int index = 0;
|
||||||
|
final int first = text.codePointAt(0);
|
||||||
|
if (!(first == '_' || Character.isAlphabetic(first))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
index += Character.charCount(first);
|
||||||
|
while (index < text.length()) {
|
||||||
|
final int codePoint = text.codePointAt(index);
|
||||||
|
if (!(codePoint == '_'
|
||||||
|
|| Character.isAlphabetic(codePoint)
|
||||||
|
|| Character.isDigit(codePoint))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
index += Character.charCount(codePoint);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
private ReadOnlyList<PbsToken> lexInternal() {
|
private ReadOnlyList<PbsToken> lexInternal() {
|
||||||
while (!isAtEnd() || state != LexerState.DEFAULT) {
|
while (!isAtEnd() || state != LexerState.DEFAULT) {
|
||||||
switch (state) {
|
switch (state) {
|
||||||
@@ -52,6 +79,7 @@ public final class PbsLexer {
|
|||||||
case IDENTIFIER -> scanIdentifierState();
|
case IDENTIFIER -> scanIdentifierState();
|
||||||
case NUMBER -> scanNumberState();
|
case NUMBER -> scanNumberState();
|
||||||
case STRING -> scanStringState();
|
case STRING -> scanStringState();
|
||||||
|
case DOC_TEXT_BLOCK -> scanDocTextBlockState();
|
||||||
case LINE_COMMENT -> scanLineCommentState();
|
case LINE_COMMENT -> scanLineCommentState();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -123,7 +151,15 @@ public final class PbsLexer {
|
|||||||
}
|
}
|
||||||
addToken(match('=') ? PbsTokenKind.SLASH_EQUAL : PbsTokenKind.SLASH);
|
addToken(match('=') ? PbsTokenKind.SLASH_EQUAL : PbsTokenKind.SLASH);
|
||||||
}
|
}
|
||||||
case '"' -> state = LexerState.STRING;
|
case '"' -> {
|
||||||
|
if (peek() == '"' && peekNext() == '"') {
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
state = LexerState.DOC_TEXT_BLOCK;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state = LexerState.STRING;
|
||||||
|
}
|
||||||
default -> {
|
default -> {
|
||||||
if (isDigit(c)) {
|
if (isDigit(c)) {
|
||||||
state = LexerState.NUMBER;
|
state = LexerState.NUMBER;
|
||||||
@@ -206,6 +242,23 @@ public final class PbsLexer {
|
|||||||
state = LexerState.DEFAULT;
|
state = LexerState.DEFAULT;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void scanDocTextBlockState() {
|
||||||
|
while (!isAtEnd()) {
|
||||||
|
if (peek() == '"' && peekNext() == '"' && peekAfterNext() == '"') {
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
addToken(PbsTokenKind.DOC_TEXT_BLOCK);
|
||||||
|
state = LexerState.DEFAULT;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
|
||||||
|
report(LexErrors.E_LEX_UNTERMINATED_DOC_TEXT_BLOCK, "Unterminated documentation text block");
|
||||||
|
state = LexerState.DEFAULT;
|
||||||
|
}
|
||||||
|
|
||||||
private void scanLineCommentState() {
|
private void scanLineCommentState() {
|
||||||
while (!isAtEnd() && peek() != '\n') {
|
while (!isAtEnd() && peek() != '\n') {
|
||||||
advance();
|
advance();
|
||||||
@@ -250,6 +303,17 @@ public final class PbsLexer {
|
|||||||
return source.codePointAt(nextIndex);
|
return source.codePointAt(nextIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private int peekAfterNext() {
|
||||||
|
if (isAtEnd()) return '\0';
|
||||||
|
final int first = source.codePointAt(current);
|
||||||
|
final int secondIndex = current + Character.charCount(first);
|
||||||
|
if (secondIndex >= source.length()) return '\0';
|
||||||
|
final int second = source.codePointAt(secondIndex);
|
||||||
|
final int thirdIndex = secondIndex + Character.charCount(second);
|
||||||
|
if (thirdIndex >= source.length()) return '\0';
|
||||||
|
return source.codePointAt(thirdIndex);
|
||||||
|
}
|
||||||
|
|
||||||
private boolean isAtEnd() {
|
private boolean isAtEnd() {
|
||||||
return current >= source.length();
|
return current >= source.length();
|
||||||
}
|
}
|
||||||
|
|||||||
+1
@@ -17,6 +17,7 @@ public enum PbsTokenKind {
|
|||||||
FLOAT_LITERAL,
|
FLOAT_LITERAL,
|
||||||
BOUNDED_LITERAL,
|
BOUNDED_LITERAL,
|
||||||
STRING_LITERAL,
|
STRING_LITERAL,
|
||||||
|
DOC_TEXT_BLOCK,
|
||||||
COMMENT,
|
COMMENT,
|
||||||
|
|
||||||
// Import keywords.
|
// Import keywords.
|
||||||
|
|||||||
+4
@@ -84,6 +84,10 @@ final class PbsAttributeParser {
|
|||||||
final var token = cursor.previous();
|
final var token = cursor.previous();
|
||||||
return new PbsAst.AttributeStringValue(token.lexeme(), context.span(token.start(), token.end()));
|
return new PbsAst.AttributeStringValue(token.lexeme(), context.span(token.start(), token.end()));
|
||||||
}
|
}
|
||||||
|
if (cursor.match(PbsTokenKind.DOC_TEXT_BLOCK)) {
|
||||||
|
final var token = cursor.previous();
|
||||||
|
return new PbsAst.AttributeDocTextBlockValue(token.lexeme(), context.span(token.start(), token.end()));
|
||||||
|
}
|
||||||
if (cursor.match(PbsTokenKind.INT_LITERAL)) {
|
if (cursor.match(PbsTokenKind.INT_LITERAL)) {
|
||||||
final var token = cursor.previous();
|
final var token = cursor.previous();
|
||||||
final var parsedLong = parseLongOrNull(token.lexeme());
|
final var parsedLong = parseLongOrNull(token.lexeme());
|
||||||
|
|||||||
+88
-40
@@ -108,28 +108,28 @@ final class PbsDeclarationParser {
|
|||||||
final PbsToken declareToken,
|
final PbsToken declareToken,
|
||||||
final ReadOnlyList<PbsAst.Attribute> pendingAttributes) {
|
final ReadOnlyList<PbsAst.Attribute> pendingAttributes) {
|
||||||
if (cursor.match(PbsTokenKind.STRUCT)) {
|
if (cursor.match(PbsTokenKind.STRUCT)) {
|
||||||
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "struct declarations");
|
rejectUnsupportedDeclarationAttributes(pendingAttributes, "struct declarations");
|
||||||
return parseStructDeclaration(declareToken);
|
return parseStructDeclaration(declareToken, pendingAttributes);
|
||||||
}
|
}
|
||||||
if (cursor.match(PbsTokenKind.CONTRACT)) {
|
if (cursor.match(PbsTokenKind.CONTRACT)) {
|
||||||
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "contract declarations");
|
rejectUnsupportedDeclarationAttributes(pendingAttributes, "contract declarations");
|
||||||
return parseContractDeclaration(declareToken);
|
return parseContractDeclaration(declareToken, pendingAttributes);
|
||||||
}
|
}
|
||||||
if (cursor.match(PbsTokenKind.SERVICE)) {
|
if (cursor.match(PbsTokenKind.SERVICE)) {
|
||||||
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "service declarations");
|
rejectUnsupportedDeclarationAttributes(pendingAttributes, "service declarations");
|
||||||
return parseServiceDeclaration(declareToken);
|
return parseServiceDeclaration(declareToken, pendingAttributes);
|
||||||
}
|
}
|
||||||
if (cursor.match(PbsTokenKind.ERROR)) {
|
if (cursor.match(PbsTokenKind.ERROR)) {
|
||||||
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "error declarations");
|
rejectUnsupportedDeclarationAttributes(pendingAttributes, "error declarations");
|
||||||
return parseErrorDeclaration(declareToken);
|
return parseErrorDeclaration(declareToken, pendingAttributes);
|
||||||
}
|
}
|
||||||
if (cursor.match(PbsTokenKind.ENUM)) {
|
if (cursor.match(PbsTokenKind.ENUM)) {
|
||||||
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "enum declarations");
|
rejectUnsupportedDeclarationAttributes(pendingAttributes, "enum declarations");
|
||||||
return parseEnumDeclaration(declareToken);
|
return parseEnumDeclaration(declareToken, pendingAttributes);
|
||||||
}
|
}
|
||||||
if (cursor.match(PbsTokenKind.CALLBACK)) {
|
if (cursor.match(PbsTokenKind.CALLBACK)) {
|
||||||
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "callback declarations");
|
rejectUnsupportedDeclarationAttributes(pendingAttributes, "callback declarations");
|
||||||
return parseCallbackDeclaration(declareToken);
|
return parseCallbackDeclaration(declareToken, pendingAttributes);
|
||||||
}
|
}
|
||||||
if (cursor.match(PbsTokenKind.GLOBAL)) {
|
if (cursor.match(PbsTokenKind.GLOBAL)) {
|
||||||
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "global declarations");
|
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "global declarations");
|
||||||
@@ -139,14 +139,14 @@ final class PbsDeclarationParser {
|
|||||||
return parseConstDeclaration(declareToken, pendingAttributes);
|
return parseConstDeclaration(declareToken, pendingAttributes);
|
||||||
}
|
}
|
||||||
if (cursor.match(PbsTokenKind.HOST)) {
|
if (cursor.match(PbsTokenKind.HOST)) {
|
||||||
rejectAttributesBeforeUnsupportedTopDecl(pendingAttributes, "host declarations");
|
rejectUnsupportedDeclarationAttributes(pendingAttributes, "host declarations");
|
||||||
if (isNotInterfaceMode()) {
|
if (isNotInterfaceMode()) {
|
||||||
final var end = declarationTerminatorDelegate.consume();
|
final var end = declarationTerminatorDelegate.consume();
|
||||||
report(cursor.previous(), ParseErrors.E_PARSE_RESERVED_DECLARATION,
|
report(cursor.previous(), ParseErrors.E_PARSE_RESERVED_DECLARATION,
|
||||||
"'declare host' is reserved and not supported in ordinary source modules");
|
"'declare host' is reserved and not supported in ordinary source modules");
|
||||||
return new PbsAst.InvalidDecl("reserved declare host", span(declareToken.start(), end));
|
return new PbsAst.InvalidDecl("reserved declare host", span(declareToken.start(), end));
|
||||||
}
|
}
|
||||||
return parseHostDeclaration(declareToken);
|
return parseHostDeclaration(declareToken, pendingAttributes);
|
||||||
}
|
}
|
||||||
if (cursor.match(PbsTokenKind.BUILTIN)) {
|
if (cursor.match(PbsTokenKind.BUILTIN)) {
|
||||||
consume(PbsTokenKind.TYPE, "Expected 'type' in 'declare builtin type' declaration");
|
consume(PbsTokenKind.TYPE, "Expected 'type' in 'declare builtin type' declaration");
|
||||||
@@ -211,14 +211,16 @@ final class PbsDeclarationParser {
|
|||||||
span(implementsToken.start(), end));
|
span(implementsToken.start(), end));
|
||||||
}
|
}
|
||||||
|
|
||||||
private PbsAst.HostDecl parseHostDeclaration(final PbsToken declareToken) {
|
private PbsAst.HostDecl parseHostDeclaration(
|
||||||
|
final PbsToken declareToken,
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected host declaration name");
|
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected host declaration name");
|
||||||
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start host declaration body");
|
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start host declaration body");
|
||||||
final var signatures = new ArrayList<PbsAst.FunctionSignature>();
|
final var signatures = new ArrayList<PbsAst.FunctionSignature>();
|
||||||
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
|
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
|
||||||
var attributes = ReadOnlyList.<PbsAst.Attribute>empty();
|
var signatureAttributes = ReadOnlyList.<PbsAst.Attribute>empty();
|
||||||
if (cursor.check(PbsTokenKind.LEFT_BRACKET)) {
|
if (cursor.check(PbsTokenKind.LEFT_BRACKET)) {
|
||||||
attributes = attributeParser.parseAttributeList();
|
signatureAttributes = attributeParser.parseAttributeList();
|
||||||
}
|
}
|
||||||
if (!cursor.match(PbsTokenKind.FN)) {
|
if (!cursor.match(PbsTokenKind.FN)) {
|
||||||
report(cursor.peek(), ParseErrors.E_PARSE_INVALID_DECL_SHAPE,
|
report(cursor.peek(), ParseErrors.E_PARSE_INVALID_DECL_SHAPE,
|
||||||
@@ -226,12 +228,13 @@ final class PbsDeclarationParser {
|
|||||||
cursor.advance();
|
cursor.advance();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
signatures.add(parseFunctionSignature(cursor.previous(), attributes));
|
signatures.add(parseFunctionSignature(cursor.previous(), signatureAttributes));
|
||||||
}
|
}
|
||||||
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end host declaration body");
|
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end host declaration body");
|
||||||
return new PbsAst.HostDecl(
|
return new PbsAst.HostDecl(
|
||||||
name.lexeme(),
|
name.lexeme(),
|
||||||
ReadOnlyList.wrap(signatures),
|
ReadOnlyList.wrap(signatures),
|
||||||
|
attributes,
|
||||||
span(declareToken.start(), rightBrace.end()));
|
span(declareToken.start(), rightBrace.end()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,7 +311,9 @@ final class PbsDeclarationParser {
|
|||||||
return fields;
|
return fields;
|
||||||
}
|
}
|
||||||
|
|
||||||
private PbsAst.StructDecl parseStructDeclaration(final PbsToken declareToken) {
|
private PbsAst.StructDecl parseStructDeclaration(
|
||||||
|
final PbsToken declareToken,
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected struct name");
|
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected struct name");
|
||||||
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' in struct declaration");
|
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' in struct declaration");
|
||||||
final var fields = parseStructFields();
|
final var fields = parseStructFields();
|
||||||
@@ -340,6 +345,7 @@ final class PbsDeclarationParser {
|
|||||||
ReadOnlyList.wrap(methods),
|
ReadOnlyList.wrap(methods),
|
||||||
ReadOnlyList.wrap(ctors),
|
ReadOnlyList.wrap(ctors),
|
||||||
hasBody,
|
hasBody,
|
||||||
|
attributes,
|
||||||
span(declareToken.start(), end));
|
span(declareToken.start(), end));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -382,10 +388,17 @@ final class PbsDeclarationParser {
|
|||||||
final var methods = new ArrayList<PbsAst.FunctionDecl>();
|
final var methods = new ArrayList<PbsAst.FunctionDecl>();
|
||||||
final var ctors = new ArrayList<PbsAst.CtorDecl>();
|
final var ctors = new ArrayList<PbsAst.CtorDecl>();
|
||||||
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
|
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
|
||||||
|
var attributes = ReadOnlyList.<PbsAst.Attribute>empty();
|
||||||
|
if (cursor.check(PbsTokenKind.LEFT_BRACKET)) {
|
||||||
|
attributes = attributeParser.parseAttributeList();
|
||||||
|
}
|
||||||
if (cursor.match(PbsTokenKind.FN)) {
|
if (cursor.match(PbsTokenKind.FN)) {
|
||||||
methods.add(parseFunctionLike(cursor.previous(), ReadOnlyList.empty()));
|
methods.add(parseFunctionLike(cursor.previous(), attributes));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (!attributes.isEmpty()) {
|
||||||
|
reportAttributesNotAllowed(attributes, "Attributes are valid only on struct methods in struct bodies");
|
||||||
|
}
|
||||||
if (cursor.match(PbsTokenKind.CTOR)) {
|
if (cursor.match(PbsTokenKind.CTOR)) {
|
||||||
ctors.add(parseCtorDeclarationInBody(cursor.previous()));
|
ctors.add(parseCtorDeclarationInBody(cursor.previous()));
|
||||||
continue;
|
continue;
|
||||||
@@ -411,17 +424,19 @@ final class PbsDeclarationParser {
|
|||||||
span(ctorToken.start(), body.span().getEnd()));
|
span(ctorToken.start(), body.span().getEnd()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private PbsAst.ContractDecl parseContractDeclaration(final PbsToken declareToken) {
|
private PbsAst.ContractDecl parseContractDeclaration(
|
||||||
|
final PbsToken declareToken,
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected contract name");
|
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected contract name");
|
||||||
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start contract body");
|
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start contract body");
|
||||||
final var signatures = new ArrayList<PbsAst.FunctionSignature>();
|
final var signatures = new ArrayList<PbsAst.FunctionSignature>();
|
||||||
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
|
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
|
||||||
var attributes = ReadOnlyList.<PbsAst.Attribute>empty();
|
var signatureAttributes = ReadOnlyList.<PbsAst.Attribute>empty();
|
||||||
if (cursor.check(PbsTokenKind.LEFT_BRACKET)) {
|
if (cursor.check(PbsTokenKind.LEFT_BRACKET)) {
|
||||||
attributes = attributeParser.parseAttributeList();
|
signatureAttributes = attributeParser.parseAttributeList();
|
||||||
if (isOrdinaryMode()) {
|
if (isOrdinaryMode()) {
|
||||||
reportAttributesNotAllowed(attributes, "Attributes are not allowed in ordinary .pbs source modules");
|
reportAttributesNotAllowed(signatureAttributes, "Attributes are not allowed in ordinary .pbs source modules");
|
||||||
attributes = ReadOnlyList.empty();
|
signatureAttributes = ReadOnlyList.empty();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!cursor.match(PbsTokenKind.FN)) {
|
if (!cursor.match(PbsTokenKind.FN)) {
|
||||||
@@ -430,30 +445,41 @@ final class PbsDeclarationParser {
|
|||||||
cursor.advance();
|
cursor.advance();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
signatures.add(parseFunctionSignature(cursor.previous(), attributes));
|
signatures.add(parseFunctionSignature(cursor.previous(), signatureAttributes));
|
||||||
}
|
}
|
||||||
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end contract body");
|
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end contract body");
|
||||||
return new PbsAst.ContractDecl(name.lexeme(), ReadOnlyList.wrap(signatures), span(declareToken.start(), rightBrace.end()));
|
return new PbsAst.ContractDecl(name.lexeme(), ReadOnlyList.wrap(signatures), attributes, span(declareToken.start(), rightBrace.end()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private PbsAst.ServiceDecl parseServiceDeclaration(final PbsToken declareToken) {
|
private PbsAst.ServiceDecl parseServiceDeclaration(
|
||||||
|
final PbsToken declareToken,
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected service name");
|
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected service name");
|
||||||
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start service body");
|
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start service body");
|
||||||
final var methods = new ArrayList<PbsAst.FunctionDecl>();
|
final var methods = new ArrayList<PbsAst.FunctionDecl>();
|
||||||
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
|
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
|
||||||
|
var methodAttributes = ReadOnlyList.<PbsAst.Attribute>empty();
|
||||||
|
if (cursor.check(PbsTokenKind.LEFT_BRACKET)) {
|
||||||
|
methodAttributes = attributeParser.parseAttributeList();
|
||||||
|
}
|
||||||
if (!cursor.match(PbsTokenKind.FN)) {
|
if (!cursor.match(PbsTokenKind.FN)) {
|
||||||
|
if (!methodAttributes.isEmpty()) {
|
||||||
|
reportAttributesNotAllowed(methodAttributes, "Attributes are valid only on service methods in service bodies");
|
||||||
|
}
|
||||||
report(cursor.peek(), ParseErrors.E_PARSE_INVALID_DECL_SHAPE,
|
report(cursor.peek(), ParseErrors.E_PARSE_INVALID_DECL_SHAPE,
|
||||||
"Service body accepts only method declarations");
|
"Service body accepts only method declarations");
|
||||||
cursor.advance();
|
cursor.advance();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
methods.add(parseFunctionLike(cursor.previous(), ReadOnlyList.empty()));
|
methods.add(parseFunctionLike(cursor.previous(), methodAttributes));
|
||||||
}
|
}
|
||||||
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end service body");
|
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end service body");
|
||||||
return new PbsAst.ServiceDecl(name.lexeme(), ReadOnlyList.wrap(methods), span(declareToken.start(), rightBrace.end()));
|
return new PbsAst.ServiceDecl(name.lexeme(), ReadOnlyList.wrap(methods), attributes, span(declareToken.start(), rightBrace.end()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private PbsAst.ErrorDecl parseErrorDeclaration(final PbsToken declareToken) {
|
private PbsAst.ErrorDecl parseErrorDeclaration(
|
||||||
|
final PbsToken declareToken,
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected error name");
|
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected error name");
|
||||||
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start error body");
|
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start error body");
|
||||||
final var cases = new ArrayList<String>();
|
final var cases = new ArrayList<String>();
|
||||||
@@ -463,10 +489,12 @@ final class PbsDeclarationParser {
|
|||||||
consume(PbsTokenKind.SEMICOLON, "Expected ';' after error case label");
|
consume(PbsTokenKind.SEMICOLON, "Expected ';' after error case label");
|
||||||
}
|
}
|
||||||
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end error body");
|
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end error body");
|
||||||
return new PbsAst.ErrorDecl(name.lexeme(), ReadOnlyList.wrap(cases), span(declareToken.start(), rightBrace.end()));
|
return new PbsAst.ErrorDecl(name.lexeme(), ReadOnlyList.wrap(cases), attributes, span(declareToken.start(), rightBrace.end()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private PbsAst.EnumDecl parseEnumDeclaration(final PbsToken declareToken) {
|
private PbsAst.EnumDecl parseEnumDeclaration(
|
||||||
|
final PbsToken declareToken,
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected enum name");
|
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected enum name");
|
||||||
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after enum name");
|
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after enum name");
|
||||||
|
|
||||||
@@ -522,7 +550,7 @@ final class PbsDeclarationParser {
|
|||||||
|
|
||||||
final var rightParen = consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after enum cases");
|
final var rightParen = consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after enum cases");
|
||||||
final var semicolon = consume(PbsTokenKind.SEMICOLON, "Expected ';' after enum declaration");
|
final var semicolon = consume(PbsTokenKind.SEMICOLON, "Expected ';' after enum declaration");
|
||||||
return new PbsAst.EnumDecl(name.lexeme(), ReadOnlyList.wrap(cases), span(declareToken.start(), Math.max(rightParen.end(), semicolon.end())));
|
return new PbsAst.EnumDecl(name.lexeme(), ReadOnlyList.wrap(cases), attributes, span(declareToken.start(), Math.max(rightParen.end(), semicolon.end())));
|
||||||
}
|
}
|
||||||
|
|
||||||
private PbsAst.FunctionDecl parseFunctionLike(
|
private PbsAst.FunctionDecl parseFunctionLike(
|
||||||
@@ -543,6 +571,7 @@ final class PbsDeclarationParser {
|
|||||||
returnSpec.kind(),
|
returnSpec.kind(),
|
||||||
returnSpec.returnType(),
|
returnSpec.returnType(),
|
||||||
returnSpec.resultErrorType(),
|
returnSpec.resultErrorType(),
|
||||||
|
pendingAttributes,
|
||||||
lifecycleMarker,
|
lifecycleMarker,
|
||||||
body,
|
body,
|
||||||
span(fnToken.start(), body.span().getEnd()));
|
span(fnToken.start(), body.span().getEnd()));
|
||||||
@@ -585,7 +614,9 @@ final class PbsDeclarationParser {
|
|||||||
return token;
|
return token;
|
||||||
}
|
}
|
||||||
|
|
||||||
private PbsAst.CallbackDecl parseCallbackDeclaration(final PbsToken declareToken) {
|
private PbsAst.CallbackDecl parseCallbackDeclaration(
|
||||||
|
final PbsToken declareToken,
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected callback name");
|
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected callback name");
|
||||||
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after callback name");
|
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after callback name");
|
||||||
final var parameters = typeParser.parseParametersUntilRightParen();
|
final var parameters = typeParser.parseParametersUntilRightParen();
|
||||||
@@ -600,6 +631,7 @@ final class PbsDeclarationParser {
|
|||||||
returnSpec.kind(),
|
returnSpec.kind(),
|
||||||
returnSpec.returnType(),
|
returnSpec.returnType(),
|
||||||
returnSpec.resultErrorType(),
|
returnSpec.resultErrorType(),
|
||||||
|
attributes,
|
||||||
span(declareToken.start(), semicolon.end()));
|
span(declareToken.start(), semicolon.end()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -651,6 +683,20 @@ final class PbsDeclarationParser {
|
|||||||
reportAttributesNotAllowed(attributes, "Attributes are not allowed before " + targetSurface);
|
reportAttributesNotAllowed(attributes, "Attributes are not allowed before " + targetSurface);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void rejectUnsupportedDeclarationAttributes(
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
|
final String targetSurface) {
|
||||||
|
for (final var attribute : attributes) {
|
||||||
|
if ("Doc".equals(attribute.name())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(),
|
||||||
|
ParseErrors.E_PARSE_ATTRIBUTES_NOT_ALLOWED.name(),
|
||||||
|
"Only [Doc] is allowed before " + targetSurface,
|
||||||
|
attribute.span());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void reportAttributesNotAllowed(
|
private void reportAttributesNotAllowed(
|
||||||
final ReadOnlyList<PbsAst.Attribute> attributes,
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
final String message) {
|
final String message) {
|
||||||
@@ -676,14 +722,16 @@ final class PbsDeclarationParser {
|
|||||||
return PbsAst.LifecycleMarker.NONE;
|
return PbsAst.LifecycleMarker.NONE;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isOrdinaryMode()) {
|
|
||||||
reportAttributesNotAllowed(attributes, "Attributes are not allowed before top-level functions");
|
|
||||||
return PbsAst.LifecycleMarker.NONE;
|
|
||||||
}
|
|
||||||
|
|
||||||
PbsAst.LifecycleMarker marker = PbsAst.LifecycleMarker.NONE;
|
PbsAst.LifecycleMarker marker = PbsAst.LifecycleMarker.NONE;
|
||||||
for (final var attribute : attributes) {
|
for (final var attribute : attributes) {
|
||||||
final PbsAst.LifecycleMarker nextMarker;
|
final PbsAst.LifecycleMarker nextMarker;
|
||||||
|
if ("Doc".equals(attribute.name())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!isOrdinaryMode()) {
|
||||||
|
reportAttributesNotAllowed(attributes, "Only [Doc] is allowed before interface executable methods");
|
||||||
|
return PbsAst.LifecycleMarker.NONE;
|
||||||
|
}
|
||||||
if ("Init".equals(attribute.name())) {
|
if ("Init".equals(attribute.name())) {
|
||||||
nextMarker = PbsAst.LifecycleMarker.INIT;
|
nextMarker = PbsAst.LifecycleMarker.INIT;
|
||||||
} else if ("Frame".equals(attribute.name())) {
|
} else if ("Frame".equals(attribute.name())) {
|
||||||
|
|||||||
+321
@@ -0,0 +1,321 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
import p.studio.utilities.structures.ReadOnlyList;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
final class PbsAstDocumentSymbols {
|
||||||
|
private PbsAstDocumentSymbols() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<PbsEditorialDocumentSymbol> list(final PbsAst.File ast) {
|
||||||
|
if (ast == null || ast.topDecls() == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> symbols = new ArrayList<>();
|
||||||
|
for (final PbsAst.TopDecl topDecl : ast.topDecls()) {
|
||||||
|
symbolFor(topDecl).ifPresent(symbols::add);
|
||||||
|
}
|
||||||
|
return List.copyOf(symbols);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> symbolFor(final PbsAst.TopDecl topDecl) {
|
||||||
|
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||||
|
return callableSymbol(
|
||||||
|
functionDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.FUNCTION,
|
||||||
|
functionDecl.parameters(),
|
||||||
|
functionDecl.returnKind(),
|
||||||
|
functionDecl.returnType(),
|
||||||
|
functionDecl.resultErrorType(),
|
||||||
|
functionDecl.span());
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||||
|
return structSymbol(structDecl);
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
serviceDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.SERVICE,
|
||||||
|
"",
|
||||||
|
serviceDecl.span(),
|
||||||
|
methodSymbols(serviceDecl.methods()));
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
contractDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.CONTRACT,
|
||||||
|
"",
|
||||||
|
contractDecl.span(),
|
||||||
|
signatureSymbols(contractDecl.signatures()));
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.HostDecl hostDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
hostDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.HOST,
|
||||||
|
"",
|
||||||
|
hostDecl.span(),
|
||||||
|
signatureSymbols(hostDecl.signatures()));
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.BuiltinTypeDecl builtinTypeDecl) {
|
||||||
|
return builtinTypeSymbol(builtinTypeDecl);
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
||||||
|
return enumSymbol(enumDecl);
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.ErrorDecl errorDecl) {
|
||||||
|
return errorSymbol(errorDecl);
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||||
|
return callableSymbol(
|
||||||
|
callbackDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.CALLBACK,
|
||||||
|
callbackDecl.parameters(),
|
||||||
|
callbackDecl.returnKind(),
|
||||||
|
callbackDecl.returnType(),
|
||||||
|
callbackDecl.resultErrorType(),
|
||||||
|
callbackDecl.span());
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.GlobalDecl globalDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
globalDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.GLOBAL,
|
||||||
|
formatTypeRef(globalDecl.explicitType()),
|
||||||
|
globalDecl.span(),
|
||||||
|
List.of());
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.ConstDecl constDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
constDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.CONST,
|
||||||
|
formatTypeRef(constDecl.explicitType()),
|
||||||
|
constDecl.span(),
|
||||||
|
List.of());
|
||||||
|
}
|
||||||
|
if (topDecl instanceof PbsAst.ImplementsDecl implementsDecl) {
|
||||||
|
return namedSymbol(
|
||||||
|
implementsDecl.contractName(),
|
||||||
|
PbsEditorialSymbolKind.CONTRACT,
|
||||||
|
implementsDecl.ownerName() == null ? "" : implementsDecl.ownerName(),
|
||||||
|
implementsDecl.span(),
|
||||||
|
methodSymbols(implementsDecl.methods()));
|
||||||
|
}
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> structSymbol(final PbsAst.StructDecl structDecl) {
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> children = new ArrayList<>();
|
||||||
|
for (final PbsAst.StructField field : structDecl.fields()) {
|
||||||
|
namedSymbol(
|
||||||
|
field.name(),
|
||||||
|
PbsEditorialSymbolKind.FIELD,
|
||||||
|
formatTypeRef(field.typeRef()),
|
||||||
|
field.span(),
|
||||||
|
List.of()).ifPresent(children::add);
|
||||||
|
}
|
||||||
|
for (final PbsAst.CtorDecl ctorDecl : structDecl.ctors()) {
|
||||||
|
namedSymbol(
|
||||||
|
ctorDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.CONSTRUCTOR,
|
||||||
|
ctorDetail(ctorDecl.parameters()),
|
||||||
|
ctorDecl.span(),
|
||||||
|
List.of()).ifPresent(children::add);
|
||||||
|
}
|
||||||
|
children.addAll(methodSymbols(structDecl.methods()));
|
||||||
|
return namedSymbol(
|
||||||
|
structDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.STRUCT,
|
||||||
|
"",
|
||||||
|
structDecl.span(),
|
||||||
|
children);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> builtinTypeSymbol(final PbsAst.BuiltinTypeDecl builtinTypeDecl) {
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> children = new ArrayList<>();
|
||||||
|
for (final PbsAst.BuiltinFieldDecl field : builtinTypeDecl.fields()) {
|
||||||
|
namedSymbol(
|
||||||
|
field.name(),
|
||||||
|
PbsEditorialSymbolKind.FIELD,
|
||||||
|
formatTypeRef(field.typeRef()),
|
||||||
|
field.span(),
|
||||||
|
List.of()).ifPresent(children::add);
|
||||||
|
}
|
||||||
|
children.addAll(signatureSymbols(builtinTypeDecl.signatures()));
|
||||||
|
return namedSymbol(
|
||||||
|
builtinTypeDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.BUILTIN_TYPE,
|
||||||
|
"",
|
||||||
|
builtinTypeDecl.span(),
|
||||||
|
children);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> enumSymbol(final PbsAst.EnumDecl enumDecl) {
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> children = new ArrayList<>();
|
||||||
|
for (final PbsAst.EnumCase enumCase : enumDecl.cases()) {
|
||||||
|
final String detail = enumCase.explicitValue() == null ? "" : String.valueOf(enumCase.explicitValue());
|
||||||
|
namedSymbol(
|
||||||
|
enumCase.name(),
|
||||||
|
PbsEditorialSymbolKind.ENUM,
|
||||||
|
detail,
|
||||||
|
enumCase.span(),
|
||||||
|
List.of()).ifPresent(children::add);
|
||||||
|
}
|
||||||
|
return namedSymbol(
|
||||||
|
enumDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.ENUM,
|
||||||
|
"",
|
||||||
|
enumDecl.span(),
|
||||||
|
children);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> errorSymbol(final PbsAst.ErrorDecl errorDecl) {
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> children = new ArrayList<>();
|
||||||
|
for (final String label : errorDecl.cases()) {
|
||||||
|
namedSymbol(
|
||||||
|
label,
|
||||||
|
PbsEditorialSymbolKind.ERROR,
|
||||||
|
"",
|
||||||
|
errorDecl.span(),
|
||||||
|
List.of()).ifPresent(children::add);
|
||||||
|
}
|
||||||
|
return namedSymbol(
|
||||||
|
errorDecl.name(),
|
||||||
|
PbsEditorialSymbolKind.ERROR,
|
||||||
|
"",
|
||||||
|
errorDecl.span(),
|
||||||
|
children);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<PbsEditorialDocumentSymbol> methodSymbols(final ReadOnlyList<PbsAst.FunctionDecl> methods) {
|
||||||
|
if (methods == null || methods.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> symbols = new ArrayList<>();
|
||||||
|
for (final PbsAst.FunctionDecl method : methods) {
|
||||||
|
callableSymbol(
|
||||||
|
method.name(),
|
||||||
|
PbsEditorialSymbolKind.METHOD,
|
||||||
|
method.parameters(),
|
||||||
|
method.returnKind(),
|
||||||
|
method.returnType(),
|
||||||
|
method.resultErrorType(),
|
||||||
|
method.span()).ifPresent(symbols::add);
|
||||||
|
}
|
||||||
|
return symbols;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<PbsEditorialDocumentSymbol> signatureSymbols(
|
||||||
|
final ReadOnlyList<PbsAst.FunctionSignature> signatures) {
|
||||||
|
if (signatures == null || signatures.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<PbsEditorialDocumentSymbol> symbols = new ArrayList<>();
|
||||||
|
for (final PbsAst.FunctionSignature signature : signatures) {
|
||||||
|
callableSymbol(
|
||||||
|
signature.name(),
|
||||||
|
PbsEditorialSymbolKind.METHOD,
|
||||||
|
signature.parameters(),
|
||||||
|
signature.returnKind(),
|
||||||
|
signature.returnType(),
|
||||||
|
signature.resultErrorType(),
|
||||||
|
signature.span()).ifPresent(symbols::add);
|
||||||
|
}
|
||||||
|
return symbols;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> callableSymbol(
|
||||||
|
final String name,
|
||||||
|
final PbsEditorialSymbolKind kind,
|
||||||
|
final ReadOnlyList<PbsAst.Parameter> parameters,
|
||||||
|
final PbsAst.ReturnKind returnKind,
|
||||||
|
final PbsAst.TypeRef returnType,
|
||||||
|
final PbsAst.TypeRef resultErrorType,
|
||||||
|
final Span span) {
|
||||||
|
return namedSymbol(
|
||||||
|
name,
|
||||||
|
kind,
|
||||||
|
callableDetail(parameters, returnKind, returnType, resultErrorType),
|
||||||
|
span,
|
||||||
|
List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<PbsEditorialDocumentSymbol> namedSymbol(
|
||||||
|
final String name,
|
||||||
|
final PbsEditorialSymbolKind kind,
|
||||||
|
final String detail,
|
||||||
|
final Span span,
|
||||||
|
final List<PbsEditorialDocumentSymbol> children) {
|
||||||
|
if (name == null || name.isBlank() || span == null || span.isNone()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.of(new PbsEditorialDocumentSymbol(name, kind, detail, span, children));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String callableDetail(
|
||||||
|
final ReadOnlyList<PbsAst.Parameter> parameters,
|
||||||
|
final PbsAst.ReturnKind returnKind,
|
||||||
|
final PbsAst.TypeRef returnType,
|
||||||
|
final PbsAst.TypeRef resultErrorType) {
|
||||||
|
return "(" + formatParameters(parameters) + ") -> " + formatReturn(returnKind, returnType, resultErrorType);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String ctorDetail(final ReadOnlyList<PbsAst.Parameter> parameters) {
|
||||||
|
return "(" + formatParameters(parameters) + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatParameters(final ReadOnlyList<PbsAst.Parameter> parameters) {
|
||||||
|
if (parameters == null || parameters.isEmpty()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
final ArrayList<String> parts = new ArrayList<>(parameters.size());
|
||||||
|
for (final PbsAst.Parameter parameter : parameters) {
|
||||||
|
parts.add(parameter.name() + ": " + formatTypeRef(parameter.typeRef()));
|
||||||
|
}
|
||||||
|
return String.join(", ", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatReturn(
|
||||||
|
final PbsAst.ReturnKind returnKind,
|
||||||
|
final PbsAst.TypeRef returnType,
|
||||||
|
final PbsAst.TypeRef resultErrorType) {
|
||||||
|
if (returnKind == null) {
|
||||||
|
return formatTypeRef(returnType);
|
||||||
|
}
|
||||||
|
return switch (returnKind) {
|
||||||
|
case INFERRED_UNIT, EXPLICIT_UNIT -> "void";
|
||||||
|
case PLAIN -> formatTypeRef(returnType);
|
||||||
|
case RESULT -> {
|
||||||
|
final String errorType = formatTypeRef(resultErrorType);
|
||||||
|
if (returnType == null || returnType.kind() == PbsAst.TypeRefKind.UNIT) {
|
||||||
|
yield "result<" + errorType + ">";
|
||||||
|
}
|
||||||
|
yield "result<" + errorType + "> " + formatTypeRef(returnType);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatTypeRef(final PbsAst.TypeRef typeRef) {
|
||||||
|
if (typeRef == null) {
|
||||||
|
return "void";
|
||||||
|
}
|
||||||
|
return switch (typeRef.kind()) {
|
||||||
|
case UNIT -> typeRef.name() == null || typeRef.name().isBlank() ? "void" : typeRef.name();
|
||||||
|
case SELF -> "Self";
|
||||||
|
case SIMPLE -> typeRef.name() == null ? "void" : typeRef.name();
|
||||||
|
case OPTIONAL -> "optional " + formatTypeRef(typeRef.inner());
|
||||||
|
case GROUP -> "(" + formatTypeRef(typeRef.inner()) + ")";
|
||||||
|
case NAMED_TUPLE -> {
|
||||||
|
final ArrayList<String> fields = new ArrayList<>(typeRef.fields().size());
|
||||||
|
for (final var field : typeRef.fields()) {
|
||||||
|
fields.add(field.label() + ": " + formatTypeRef(field.typeRef()));
|
||||||
|
}
|
||||||
|
yield "(" + String.join(", ", fields) + ")";
|
||||||
|
}
|
||||||
|
case ERROR -> "unknown";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
final class PbsAstWorkspaceSymbols {
|
||||||
|
private PbsAstWorkspaceSymbols() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<PbsEditorialWorkspaceSymbol> list(
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final String query) {
|
||||||
|
if (ast == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<PbsEditorialWorkspaceSymbol> symbols = new ArrayList<>();
|
||||||
|
for (final PbsEditorialDocumentSymbol topDecl : PbsAstDocumentSymbols.list(ast)) {
|
||||||
|
flatten(topDecl, "", query, symbols);
|
||||||
|
}
|
||||||
|
return List.copyOf(symbols);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void flatten(
|
||||||
|
final PbsEditorialDocumentSymbol symbol,
|
||||||
|
final String containerName,
|
||||||
|
final String query,
|
||||||
|
final ArrayList<PbsEditorialWorkspaceSymbol> symbols) {
|
||||||
|
if (matches(symbol.name(), query)) {
|
||||||
|
symbols.add(new PbsEditorialWorkspaceSymbol(
|
||||||
|
symbol.name(),
|
||||||
|
symbol.kind(),
|
||||||
|
symbol.detail(),
|
||||||
|
containerName,
|
||||||
|
symbol.span()));
|
||||||
|
}
|
||||||
|
for (final PbsEditorialDocumentSymbol child : symbol.children()) {
|
||||||
|
flatten(child, symbol.name(), query, symbols);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean matches(
|
||||||
|
final String name,
|
||||||
|
final String query) {
|
||||||
|
if (name == null || name.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (query == null || query.isBlank()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return name.toLowerCase(Locale.ROOT).contains(query.trim().toLowerCase(Locale.ROOT));
|
||||||
|
}
|
||||||
|
}
|
||||||
+81
-6
@@ -1,6 +1,7 @@
|
|||||||
package p.studio.compiler.pbs.semantics;
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
import p.studio.compiler.models.SourceKind;
|
import p.studio.compiler.models.SourceKind;
|
||||||
|
import p.studio.compiler.pbs.PbsDocumentationTextBlockNormalizer;
|
||||||
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
||||||
import p.studio.compiler.pbs.ast.PbsAst;
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
import p.studio.compiler.source.Span;
|
import p.studio.compiler.source.Span;
|
||||||
@@ -19,6 +20,7 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
private static final String ATTR_INTRINSIC_CALL = "IntrinsicCall";
|
private static final String ATTR_INTRINSIC_CALL = "IntrinsicCall";
|
||||||
private static final String ATTR_INIT_ALLOWED = "InitAllowed";
|
private static final String ATTR_INIT_ALLOWED = "InitAllowed";
|
||||||
private static final String ATTR_ASSET_LOWERING = "AssetLowering";
|
private static final String ATTR_ASSET_LOWERING = "AssetLowering";
|
||||||
|
private static final String ATTR_DOC = "Doc";
|
||||||
|
|
||||||
private static final Set<String> RESERVED_ATTRIBUTES = Set.of(
|
private static final Set<String> RESERVED_ATTRIBUTES = Set.of(
|
||||||
ATTR_HOST,
|
ATTR_HOST,
|
||||||
@@ -27,7 +29,8 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
ATTR_BUILTIN_CONST,
|
ATTR_BUILTIN_CONST,
|
||||||
ATTR_INTRINSIC_CALL,
|
ATTR_INTRINSIC_CALL,
|
||||||
ATTR_INIT_ALLOWED,
|
ATTR_INIT_ALLOWED,
|
||||||
ATTR_ASSET_LOWERING);
|
ATTR_ASSET_LOWERING,
|
||||||
|
ATTR_DOC);
|
||||||
|
|
||||||
private final NameTable nameTable;
|
private final NameTable nameTable;
|
||||||
private final PbsConstSemanticsValidator constSemanticsValidator = new PbsConstSemanticsValidator();
|
private final PbsConstSemanticsValidator constSemanticsValidator = new PbsConstSemanticsValidator();
|
||||||
@@ -60,6 +63,7 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
|
|
||||||
for (final var topDecl : ast.topDecls()) {
|
for (final var topDecl : ast.topDecls()) {
|
||||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||||
|
validateDocAttributes(functionDecl.attributes(), "function declarations", diagnostics);
|
||||||
if (interfaceModule) {
|
if (interfaceModule) {
|
||||||
reportInterfaceNonDeclarativeDecl(
|
reportInterfaceNonDeclarativeDecl(
|
||||||
functionDecl.span(),
|
functionDecl.span(),
|
||||||
@@ -82,6 +86,7 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||||
|
validateDocAttributes(structDecl.attributes(), "struct declarations", diagnostics);
|
||||||
binder.registerType(structDecl.name(), structDecl.span(), "struct");
|
binder.registerType(structDecl.name(), structDecl.span(), "struct");
|
||||||
if (interfaceModule && (structDecl.hasBody() || !structDecl.methods().isEmpty() || !structDecl.ctors().isEmpty())) {
|
if (interfaceModule && (structDecl.hasBody() || !structDecl.methods().isEmpty() || !structDecl.ctors().isEmpty())) {
|
||||||
reportInterfaceNonDeclarativeDecl(
|
reportInterfaceNonDeclarativeDecl(
|
||||||
@@ -94,6 +99,7 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||||
|
validateDocAttributes(serviceDecl.attributes(), "service declarations", diagnostics);
|
||||||
binder.registerType(serviceDecl.name(), serviceDecl.span(), "service");
|
binder.registerType(serviceDecl.name(), serviceDecl.span(), "service");
|
||||||
binder.registerValue(serviceDecl.name(), serviceDecl.span(), "service singleton");
|
binder.registerValue(serviceDecl.name(), serviceDecl.span(), "service singleton");
|
||||||
binder.registerVisibleTopLevelSurface(serviceDecl.name(), serviceDecl.span(), "service");
|
binder.registerVisibleTopLevelSurface(serviceDecl.name(), serviceDecl.span(), "service");
|
||||||
@@ -102,10 +108,12 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
||||||
|
validateDocAttributes(contractDecl.attributes(), "contract declarations", diagnostics);
|
||||||
binder.registerType(contractDecl.name(), contractDecl.span(), "contract");
|
binder.registerType(contractDecl.name(), contractDecl.span(), "contract");
|
||||||
if (interfaceModule) {
|
if (interfaceModule) {
|
||||||
for (final var signature : contractDecl.signatures()) {
|
for (final var signature : contractDecl.signatures()) {
|
||||||
validateReservedAttributeTarget(signature.attributes(), "contract signature", diagnostics);
|
validateDocAttributes(signature.attributes(), "contract signatures", diagnostics);
|
||||||
|
validateReservedAttributeTargetExceptDoc(signature.attributes(), "contract signature", diagnostics);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
validateContractDeclaration(contractDecl, binder, rules);
|
validateContractDeclaration(contractDecl, binder, rules);
|
||||||
@@ -113,6 +121,7 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (topDecl instanceof PbsAst.HostDecl hostDecl) {
|
if (topDecl instanceof PbsAst.HostDecl hostDecl) {
|
||||||
|
validateDocAttributes(hostDecl.attributes(), "host declarations", diagnostics);
|
||||||
binder.registerHostOwner(hostDecl.name(), hostDecl.span(), "host owner");
|
binder.registerHostOwner(hostDecl.name(), hostDecl.span(), "host owner");
|
||||||
validateHostDeclaration(hostDecl, binder, rules, interfaceModule, diagnostics);
|
validateHostDeclaration(hostDecl, binder, rules, interfaceModule, diagnostics);
|
||||||
continue;
|
continue;
|
||||||
@@ -125,18 +134,21 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (topDecl instanceof PbsAst.ErrorDecl errorDecl) {
|
if (topDecl instanceof PbsAst.ErrorDecl errorDecl) {
|
||||||
|
validateDocAttributes(errorDecl.attributes(), "error declarations", diagnostics);
|
||||||
binder.registerType(errorDecl.name(), errorDecl.span(), "error");
|
binder.registerType(errorDecl.name(), errorDecl.span(), "error");
|
||||||
rules.validateErrorDeclaration(errorDecl);
|
rules.validateErrorDeclaration(errorDecl);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
||||||
|
validateDocAttributes(enumDecl.attributes(), "enum declarations", diagnostics);
|
||||||
binder.registerType(enumDecl.name(), enumDecl.span(), "enum");
|
binder.registerType(enumDecl.name(), enumDecl.span(), "enum");
|
||||||
rules.validateEnumDeclaration(enumDecl);
|
rules.validateEnumDeclaration(enumDecl);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
if (topDecl instanceof PbsAst.CallbackDecl callbackDecl) {
|
||||||
|
validateDocAttributes(callbackDecl.attributes(), "callback declarations", diagnostics);
|
||||||
binder.registerType(callbackDecl.name(), callbackDecl.span(), "callback");
|
binder.registerType(callbackDecl.name(), callbackDecl.span(), "callback");
|
||||||
rules.validateCallbackDeclaration(callbackDecl);
|
rules.validateCallbackDeclaration(callbackDecl);
|
||||||
continue;
|
continue;
|
||||||
@@ -187,6 +199,7 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
false);
|
false);
|
||||||
final var methodScope = PbsCallableScope.structMethods(ownerNameId);
|
final var methodScope = PbsCallableScope.structMethods(ownerNameId);
|
||||||
for (final var method : structDecl.methods()) {
|
for (final var method : structDecl.methods()) {
|
||||||
|
validateDocAttributes(method.attributes(), "struct methods", diagnostics);
|
||||||
validateCallable(
|
validateCallable(
|
||||||
methodScope,
|
methodScope,
|
||||||
method.name(),
|
method.name(),
|
||||||
@@ -226,6 +239,7 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
final DiagnosticSink diagnostics) {
|
final DiagnosticSink diagnostics) {
|
||||||
final var methodScope = PbsCallableScope.serviceMethods(nameTable.register(serviceDecl.name()));
|
final var methodScope = PbsCallableScope.serviceMethods(nameTable.register(serviceDecl.name()));
|
||||||
for (final var method : serviceDecl.methods()) {
|
for (final var method : serviceDecl.methods()) {
|
||||||
|
validateDocAttributes(method.attributes(), "service methods", diagnostics);
|
||||||
validateCallable(
|
validateCallable(
|
||||||
methodScope,
|
methodScope,
|
||||||
method.name(),
|
method.name(),
|
||||||
@@ -494,12 +508,13 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
final PbsAst.ConstDecl constDecl,
|
final PbsAst.ConstDecl constDecl,
|
||||||
final boolean interfaceModule,
|
final boolean interfaceModule,
|
||||||
final DiagnosticSink diagnostics) {
|
final DiagnosticSink diagnostics) {
|
||||||
|
validateDocAttributes(constDecl.attributes(), "const declarations", diagnostics);
|
||||||
final var builtinConstAttributes = attributesNamed(constDecl.attributes(), ATTR_BUILTIN_CONST);
|
final var builtinConstAttributes = attributesNamed(constDecl.attributes(), ATTR_BUILTIN_CONST);
|
||||||
for (final var attribute : constDecl.attributes()) {
|
for (final var attribute : constDecl.attributes()) {
|
||||||
if (!isReservedAttribute(attribute.name())) {
|
if (!isReservedAttribute(attribute.name())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (ATTR_BUILTIN_CONST.equals(attribute.name())) {
|
if (ATTR_BUILTIN_CONST.equals(attribute.name()) || ATTR_DOC.equals(attribute.name())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
reportInvalidReservedAttributeTarget(
|
reportInvalidReservedAttributeTarget(
|
||||||
@@ -540,6 +555,7 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
private void validateHostSignatureAttributes(
|
private void validateHostSignatureAttributes(
|
||||||
final PbsAst.FunctionSignature signature,
|
final PbsAst.FunctionSignature signature,
|
||||||
final DiagnosticSink diagnostics) {
|
final DiagnosticSink diagnostics) {
|
||||||
|
validateDocAttributes(signature.attributes(), "host signatures", diagnostics);
|
||||||
final var hostAttributes = attributesNamed(signature.attributes(), ATTR_HOST);
|
final var hostAttributes = attributesNamed(signature.attributes(), ATTR_HOST);
|
||||||
final var initAllowedAttributes = attributesNamed(signature.attributes(), ATTR_INIT_ALLOWED);
|
final var initAllowedAttributes = attributesNamed(signature.attributes(), ATTR_INIT_ALLOWED);
|
||||||
final var assetLoweringAttributes = attributesNamed(signature.attributes(), ATTR_ASSET_LOWERING);
|
final var assetLoweringAttributes = attributesNamed(signature.attributes(), ATTR_ASSET_LOWERING);
|
||||||
@@ -550,7 +566,8 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
if (ATTR_HOST.equals(attribute.name())
|
if (ATTR_HOST.equals(attribute.name())
|
||||||
|| ATTR_CAPABILITY.equals(attribute.name())
|
|| ATTR_CAPABILITY.equals(attribute.name())
|
||||||
|| ATTR_INIT_ALLOWED.equals(attribute.name())
|
|| ATTR_INIT_ALLOWED.equals(attribute.name())
|
||||||
|| ATTR_ASSET_LOWERING.equals(attribute.name())) {
|
|| ATTR_ASSET_LOWERING.equals(attribute.name())
|
||||||
|
|| ATTR_DOC.equals(attribute.name())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
reportInvalidReservedAttributeTarget(
|
reportInvalidReservedAttributeTarget(
|
||||||
@@ -597,12 +614,13 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
private void validateBuiltinTypeAttribute(
|
private void validateBuiltinTypeAttribute(
|
||||||
final PbsAst.BuiltinTypeDecl builtinTypeDecl,
|
final PbsAst.BuiltinTypeDecl builtinTypeDecl,
|
||||||
final DiagnosticSink diagnostics) {
|
final DiagnosticSink diagnostics) {
|
||||||
|
validateDocAttributes(builtinTypeDecl.attributes(), "builtin type declarations", diagnostics);
|
||||||
final var builtinTypeAttributes = attributesNamed(builtinTypeDecl.attributes(), ATTR_BUILTIN_TYPE);
|
final var builtinTypeAttributes = attributesNamed(builtinTypeDecl.attributes(), ATTR_BUILTIN_TYPE);
|
||||||
for (final var attribute : builtinTypeDecl.attributes()) {
|
for (final var attribute : builtinTypeDecl.attributes()) {
|
||||||
if (!isReservedAttribute(attribute.name())) {
|
if (!isReservedAttribute(attribute.name())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (ATTR_BUILTIN_TYPE.equals(attribute.name())) {
|
if (ATTR_BUILTIN_TYPE.equals(attribute.name()) || ATTR_DOC.equals(attribute.name())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
reportInvalidReservedAttributeTarget(
|
reportInvalidReservedAttributeTarget(
|
||||||
@@ -645,12 +663,13 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
private void validateIntrinsicCallAttributes(
|
private void validateIntrinsicCallAttributes(
|
||||||
final PbsAst.FunctionSignature signature,
|
final PbsAst.FunctionSignature signature,
|
||||||
final DiagnosticSink diagnostics) {
|
final DiagnosticSink diagnostics) {
|
||||||
|
validateDocAttributes(signature.attributes(), "builtin method signatures", diagnostics);
|
||||||
final var intrinsicAttributes = attributesNamed(signature.attributes(), ATTR_INTRINSIC_CALL);
|
final var intrinsicAttributes = attributesNamed(signature.attributes(), ATTR_INTRINSIC_CALL);
|
||||||
for (final var attribute : signature.attributes()) {
|
for (final var attribute : signature.attributes()) {
|
||||||
if (!isReservedAttribute(attribute.name())) {
|
if (!isReservedAttribute(attribute.name())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (ATTR_INTRINSIC_CALL.equals(attribute.name())) {
|
if (ATTR_INTRINSIC_CALL.equals(attribute.name()) || ATTR_DOC.equals(attribute.name())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
reportInvalidReservedAttributeTarget(
|
reportInvalidReservedAttributeTarget(
|
||||||
@@ -770,6 +789,47 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void validateDocAttributes(
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
|
final String targetSurface,
|
||||||
|
final DiagnosticSink diagnostics) {
|
||||||
|
final var docAttributes = attributesNamed(attributes, ATTR_DOC);
|
||||||
|
if (docAttributes.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (docAttributes.size() > 1) {
|
||||||
|
for (int i = 1; i < docAttributes.size(); i++) {
|
||||||
|
reportDuplicateReservedAttribute(docAttributes.get(i), ATTR_DOC, diagnostics);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
validateDocAttributeShape(docAttributes.getFirst(), targetSurface, diagnostics);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateDocAttributeShape(
|
||||||
|
final PbsAst.Attribute attribute,
|
||||||
|
final String targetSurface,
|
||||||
|
final DiagnosticSink diagnostics) {
|
||||||
|
final var args = validateNamedArguments(attribute, Set.of("markdown"), Set.of(), diagnostics);
|
||||||
|
if (args == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final var value = args.get("markdown");
|
||||||
|
if (!(value instanceof PbsAst.AttributeDocTextBlockValue docValue)) {
|
||||||
|
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
|
||||||
|
PbsSemanticsErrors.E_SEM_MALFORMED_RESERVED_ATTRIBUTE.name(),
|
||||||
|
"Doc.markdown on %s must be a documentation text block".formatted(targetSurface),
|
||||||
|
attribute.span());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final var normalized = PbsDocumentationTextBlockNormalizer.normalizeLexeme(docValue.value());
|
||||||
|
if (normalized.isBlank()) {
|
||||||
|
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
|
||||||
|
PbsSemanticsErrors.E_SEM_MALFORMED_RESERVED_ATTRIBUTE.name(),
|
||||||
|
"Doc.markdown on %s must not be empty".formatted(targetSurface),
|
||||||
|
attribute.span());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private Map<String, PbsAst.AttributeValue> validateNamedArguments(
|
private Map<String, PbsAst.AttributeValue> validateNamedArguments(
|
||||||
final PbsAst.Attribute attribute,
|
final PbsAst.Attribute attribute,
|
||||||
final Set<String> requiredNames,
|
final Set<String> requiredNames,
|
||||||
@@ -911,6 +971,21 @@ public final class PbsDeclarationSemanticsValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void validateReservedAttributeTargetExceptDoc(
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
|
final String targetSurface,
|
||||||
|
final DiagnosticSink diagnostics) {
|
||||||
|
for (final var attribute : attributes) {
|
||||||
|
if (!isReservedAttribute(attribute.name()) || ATTR_DOC.equals(attribute.name())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
reportInvalidReservedAttributeTarget(
|
||||||
|
attribute,
|
||||||
|
"Attribute '%s' is not valid on %s".formatted(attribute.name(), targetSurface),
|
||||||
|
diagnostics);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void reportInvalidReservedAttributeTarget(
|
private void reportInvalidReservedAttributeTarget(
|
||||||
final PbsAst.Attribute attribute,
|
final PbsAst.Attribute attribute,
|
||||||
final String message,
|
final String message,
|
||||||
|
|||||||
+11
-1
@@ -6,12 +6,22 @@ public record PbsEditorialCompletionCandidate(
|
|||||||
String label,
|
String label,
|
||||||
PbsEditorialSymbolKind kind,
|
PbsEditorialSymbolKind kind,
|
||||||
String detail,
|
String detail,
|
||||||
String origin) {
|
String origin,
|
||||||
|
String documentation) {
|
||||||
|
public PbsEditorialCompletionCandidate(
|
||||||
|
final String label,
|
||||||
|
final PbsEditorialSymbolKind kind,
|
||||||
|
final String detail,
|
||||||
|
final String origin) {
|
||||||
|
this(label, kind, detail, origin, "");
|
||||||
|
}
|
||||||
|
|
||||||
public PbsEditorialCompletionCandidate {
|
public PbsEditorialCompletionCandidate {
|
||||||
label = requireText(label, "label");
|
label = requireText(label, "label");
|
||||||
kind = Objects.requireNonNull(kind, "kind");
|
kind = Objects.requireNonNull(kind, "kind");
|
||||||
detail = normalize(detail);
|
detail = normalize(detail);
|
||||||
origin = normalize(origin);
|
origin = normalize(origin);
|
||||||
|
documentation = normalize(documentation);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String requireText(
|
private static String requireText(
|
||||||
|
|||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record PbsEditorialDocumentSymbol(
|
||||||
|
String name,
|
||||||
|
PbsEditorialSymbolKind kind,
|
||||||
|
String detail,
|
||||||
|
Span span,
|
||||||
|
List<PbsEditorialDocumentSymbol> children) {
|
||||||
|
|
||||||
|
public PbsEditorialDocumentSymbol {
|
||||||
|
name = Objects.requireNonNull(name, "name").trim();
|
||||||
|
kind = Objects.requireNonNull(kind, "kind");
|
||||||
|
detail = detail == null ? "" : detail;
|
||||||
|
span = Objects.requireNonNull(span, "span");
|
||||||
|
children = children == null ? List.of() : List.copyOf(children);
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record PbsEditorialLocation(Span span) {
|
||||||
|
public PbsEditorialLocation {
|
||||||
|
Objects.requireNonNull(span, "span");
|
||||||
|
}
|
||||||
|
}
|
||||||
+40
@@ -0,0 +1,40 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record PbsEditorialRename(
|
||||||
|
String refusal,
|
||||||
|
PbsEditorialLocation placeholder,
|
||||||
|
List<PbsEditorialLocation> identity,
|
||||||
|
List<PbsEditorialLocation> sites) {
|
||||||
|
|
||||||
|
public PbsEditorialRename {
|
||||||
|
refusal = refusal == null ? "" : refusal;
|
||||||
|
identity = identity == null ? List.of() : List.copyOf(identity);
|
||||||
|
sites = sites == null ? List.of() : List.copyOf(sites);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PbsEditorialRename refused(final String reason) {
|
||||||
|
return new PbsEditorialRename(
|
||||||
|
reason == null || reason.isBlank() ? "not renameable" : reason,
|
||||||
|
null,
|
||||||
|
List.of(),
|
||||||
|
List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PbsEditorialRename applied(
|
||||||
|
final PbsEditorialLocation placeholder,
|
||||||
|
final List<PbsEditorialLocation> identity,
|
||||||
|
final List<PbsEditorialLocation> sites) {
|
||||||
|
return new PbsEditorialRename(
|
||||||
|
"",
|
||||||
|
Objects.requireNonNull(placeholder, "placeholder"),
|
||||||
|
identity,
|
||||||
|
sites);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean allowed() {
|
||||||
|
return refusal.isBlank() && placeholder != null && !identity.isEmpty() && !sites.isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
+920
-18
File diff suppressed because it is too large
Load Diff
+21
@@ -0,0 +1,21 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record PbsEditorialWorkspaceSymbol(
|
||||||
|
String name,
|
||||||
|
PbsEditorialSymbolKind kind,
|
||||||
|
String detail,
|
||||||
|
String containerName,
|
||||||
|
Span span) {
|
||||||
|
|
||||||
|
public PbsEditorialWorkspaceSymbol {
|
||||||
|
name = Objects.requireNonNull(name, "name").trim();
|
||||||
|
kind = Objects.requireNonNull(kind, "kind");
|
||||||
|
detail = detail == null ? "" : detail;
|
||||||
|
containerName = containerName == null ? "" : containerName.trim();
|
||||||
|
span = Objects.requireNonNull(span, "span");
|
||||||
|
}
|
||||||
|
}
|
||||||
+35
-11
@@ -146,7 +146,8 @@ final class PbsFlowSemanticSupport {
|
|||||||
List<CallableParameter> parameters,
|
List<CallableParameter> parameters,
|
||||||
List<TypeView> inputTypes,
|
List<TypeView> inputTypes,
|
||||||
TypeView outputType,
|
TypeView outputType,
|
||||||
Span span) {
|
Span span,
|
||||||
|
String documentation) {
|
||||||
}
|
}
|
||||||
|
|
||||||
record CallableParameter(
|
record CallableParameter(
|
||||||
@@ -282,7 +283,8 @@ final class PbsFlowSemanticSupport {
|
|||||||
method.returnKind(),
|
method.returnKind(),
|
||||||
method.returnType(),
|
method.returnType(),
|
||||||
method.resultErrorType(),
|
method.resultErrorType(),
|
||||||
method.span()));
|
method.span(),
|
||||||
|
documentationFromAttributes(method.attributes())));
|
||||||
}
|
}
|
||||||
structs.put(structDecl.name(), new StructInfo(fields, methods));
|
structs.put(structDecl.name(), new StructInfo(fields, methods));
|
||||||
return;
|
return;
|
||||||
@@ -306,7 +308,8 @@ final class PbsFlowSemanticSupport {
|
|||||||
signature.returnKind(),
|
signature.returnKind(),
|
||||||
signature.returnType(),
|
signature.returnType(),
|
||||||
signature.resultErrorType(),
|
signature.resultErrorType(),
|
||||||
signature.span()));
|
signature.span(),
|
||||||
|
documentationFromAttributes(signature.attributes())));
|
||||||
}
|
}
|
||||||
structs.put(builtinTypeDecl.name(), new StructInfo(fields, methods));
|
structs.put(builtinTypeDecl.name(), new StructInfo(fields, methods));
|
||||||
return;
|
return;
|
||||||
@@ -321,7 +324,8 @@ final class PbsFlowSemanticSupport {
|
|||||||
method.returnKind(),
|
method.returnKind(),
|
||||||
method.returnType(),
|
method.returnType(),
|
||||||
method.resultErrorType(),
|
method.resultErrorType(),
|
||||||
method.span()));
|
method.span(),
|
||||||
|
documentationFromAttributes(method.attributes())));
|
||||||
}
|
}
|
||||||
services.put(serviceDecl.name(), new ServiceInfo(methods));
|
services.put(serviceDecl.name(), new ServiceInfo(methods));
|
||||||
serviceSingletons.put(serviceDecl.name(), TypeView.service(serviceDecl.name()));
|
serviceSingletons.put(serviceDecl.name(), TypeView.service(serviceDecl.name()));
|
||||||
@@ -337,7 +341,8 @@ final class PbsFlowSemanticSupport {
|
|||||||
signature.returnKind(),
|
signature.returnKind(),
|
||||||
signature.returnType(),
|
signature.returnType(),
|
||||||
signature.resultErrorType(),
|
signature.resultErrorType(),
|
||||||
signature.span()));
|
signature.span(),
|
||||||
|
documentationFromAttributes(signature.attributes())));
|
||||||
}
|
}
|
||||||
// Host owners are value singletons with callable members, same access shape as services.
|
// Host owners are value singletons with callable members, same access shape as services.
|
||||||
services.put(hostDecl.name(), new ServiceInfo(methods));
|
services.put(hostDecl.name(), new ServiceInfo(methods));
|
||||||
@@ -354,7 +359,8 @@ final class PbsFlowSemanticSupport {
|
|||||||
signature.returnKind(),
|
signature.returnKind(),
|
||||||
signature.returnType(),
|
signature.returnType(),
|
||||||
signature.resultErrorType(),
|
signature.resultErrorType(),
|
||||||
signature.span()));
|
signature.span(),
|
||||||
|
documentationFromAttributes(signature.attributes())));
|
||||||
}
|
}
|
||||||
contracts.put(contractDecl.name(), new ContractInfo(methods));
|
contracts.put(contractDecl.name(), new ContractInfo(methods));
|
||||||
return;
|
return;
|
||||||
@@ -367,12 +373,14 @@ final class PbsFlowSemanticSupport {
|
|||||||
functionDecl.returnKind(),
|
functionDecl.returnKind(),
|
||||||
functionDecl.returnType(),
|
functionDecl.returnType(),
|
||||||
functionDecl.resultErrorType(),
|
functionDecl.resultErrorType(),
|
||||||
functionDecl.span()));
|
functionDecl.span(),
|
||||||
|
documentationFromAttributes(functionDecl.attributes())));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (topDecl instanceof PbsAst.CallbackDecl(
|
if (topDecl instanceof PbsAst.CallbackDecl(
|
||||||
String name, ReadOnlyList<PbsAst.Parameter> parameters, PbsAst.ReturnKind returnKind,
|
String name, ReadOnlyList<PbsAst.Parameter> parameters, PbsAst.ReturnKind returnKind,
|
||||||
PbsAst.TypeRef returnType, PbsAst.TypeRef resultErrorType, Span span
|
PbsAst.TypeRef returnType, PbsAst.TypeRef resultErrorType,
|
||||||
|
ReadOnlyList<PbsAst.Attribute> ignoredAttributes, Span span
|
||||||
)) {
|
)) {
|
||||||
final var symbol = callableFrom(
|
final var symbol = callableFrom(
|
||||||
name,
|
name,
|
||||||
@@ -380,7 +388,8 @@ final class PbsFlowSemanticSupport {
|
|||||||
returnKind,
|
returnKind,
|
||||||
returnType,
|
returnType,
|
||||||
resultErrorType,
|
resultErrorType,
|
||||||
span);
|
span,
|
||||||
|
"");
|
||||||
callbacks.put(name, new CallbackSignature(symbol.inputTypes(), symbol.outputType()));
|
callbacks.put(name, new CallbackSignature(symbol.inputTypes(), symbol.outputType()));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -477,7 +486,8 @@ final class PbsFlowSemanticSupport {
|
|||||||
final PbsAst.ReturnKind returnKind,
|
final PbsAst.ReturnKind returnKind,
|
||||||
final PbsAst.TypeRef returnType,
|
final PbsAst.TypeRef returnType,
|
||||||
final PbsAst.TypeRef resultErrorType,
|
final PbsAst.TypeRef resultErrorType,
|
||||||
final Span span) {
|
final Span span,
|
||||||
|
final String documentation) {
|
||||||
final var input = new ArrayList<TypeView>(parameters.size());
|
final var input = new ArrayList<TypeView>(parameters.size());
|
||||||
final var semanticParameters = new ArrayList<CallableParameter>(parameters.size());
|
final var semanticParameters = new ArrayList<CallableParameter>(parameters.size());
|
||||||
for (int index = 0; index < parameters.size(); index += 1) {
|
for (int index = 0; index < parameters.size(); index += 1) {
|
||||||
@@ -490,7 +500,21 @@ final class PbsFlowSemanticSupport {
|
|||||||
type,
|
type,
|
||||||
parameter.span()));
|
parameter.span()));
|
||||||
}
|
}
|
||||||
return new CallableSymbol(name, semanticParameters, input, callableReturn(returnKind, returnType, resultErrorType), span);
|
return new CallableSymbol(name, semanticParameters, input, callableReturn(returnKind, returnType, resultErrorType), span, documentation);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String documentationFromAttributes(final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||||
|
for (final var attribute : attributes) {
|
||||||
|
if (!"Doc".equals(attribute.name()) || attribute.arguments().isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final var argument = attribute.arguments().getFirst();
|
||||||
|
if (!"markdown".equals(argument.name()) || !(argument.value() instanceof PbsAst.AttributeDocTextBlockValue docValue)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return p.studio.compiler.pbs.PbsDocumentationTextBlockNormalizer.normalizeLexeme(docValue.value());
|
||||||
|
}
|
||||||
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
private TypeView callableReturn(
|
private TypeView callableReturn(
|
||||||
|
|||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public record PbsQuickFix(
|
||||||
|
String diagnosticCode,
|
||||||
|
int startOffset,
|
||||||
|
int endOffset,
|
||||||
|
String newText,
|
||||||
|
String title) {
|
||||||
|
|
||||||
|
public PbsQuickFix {
|
||||||
|
diagnosticCode = requireText(diagnosticCode, "diagnosticCode");
|
||||||
|
title = requireText(title, "title");
|
||||||
|
if (startOffset < 0) {
|
||||||
|
throw new IllegalArgumentException("startOffset must not be negative");
|
||||||
|
}
|
||||||
|
if (endOffset < startOffset) {
|
||||||
|
throw new IllegalArgumentException("endOffset must not be before startOffset");
|
||||||
|
}
|
||||||
|
newText = Objects.requireNonNull(newText, "newText");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String requireText(
|
||||||
|
final String value,
|
||||||
|
final String field) {
|
||||||
|
final String candidate = Objects.requireNonNull(value, field).trim();
|
||||||
|
if (candidate.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException(field + " must not be blank");
|
||||||
|
}
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
+148
@@ -0,0 +1,148 @@
|
|||||||
|
package p.studio.compiler.pbs.semantics;
|
||||||
|
|
||||||
|
import p.studio.compiler.pbs.ast.PbsAst;
|
||||||
|
import p.studio.compiler.source.Span;
|
||||||
|
import p.studio.utilities.structures.ReadOnlyList;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class PbsQuickFixCollector {
|
||||||
|
static final String REMOVE_DUPLICATE_TITLE = "Remove duplicate reserved attribute";
|
||||||
|
static final String REMOVE_INIT_ALLOWED_ARGUMENTS_TITLE = "Remove InitAllowed arguments";
|
||||||
|
private static final String INIT_ALLOWED_REPLACEMENT = "[InitAllowed]";
|
||||||
|
|
||||||
|
private PbsQuickFixCollector() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<PbsQuickFix> collect(
|
||||||
|
final PbsAst.File ast,
|
||||||
|
final boolean interfaceModule) {
|
||||||
|
if (ast == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
final ArrayList<PbsQuickFix> repairs = new ArrayList<>();
|
||||||
|
for (final PbsAst.TopDecl topDecl : ast.topDecls()) {
|
||||||
|
switch (topDecl) {
|
||||||
|
case PbsAst.FunctionDecl functionDecl -> duplicateDoc(functionDecl.attributes(), repairs);
|
||||||
|
case PbsAst.StructDecl structDecl -> {
|
||||||
|
duplicateDoc(structDecl.attributes(), repairs);
|
||||||
|
for (final PbsAst.FunctionDecl method : structDecl.methods()) {
|
||||||
|
duplicateDoc(method.attributes(), repairs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.ServiceDecl serviceDecl -> {
|
||||||
|
duplicateDoc(serviceDecl.attributes(), repairs);
|
||||||
|
for (final PbsAst.FunctionDecl method : serviceDecl.methods()) {
|
||||||
|
duplicateDoc(method.attributes(), repairs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.ContractDecl contractDecl -> {
|
||||||
|
duplicateDoc(contractDecl.attributes(), repairs);
|
||||||
|
if (interfaceModule) {
|
||||||
|
for (final PbsAst.FunctionSignature signature : contractDecl.signatures()) {
|
||||||
|
duplicateDoc(signature.attributes(), repairs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.HostDecl hostDecl -> {
|
||||||
|
duplicateDoc(hostDecl.attributes(), repairs);
|
||||||
|
if (interfaceModule) {
|
||||||
|
for (final PbsAst.FunctionSignature signature : hostDecl.signatures()) {
|
||||||
|
collectHostSignature(signature, repairs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.BuiltinTypeDecl builtinTypeDecl -> {
|
||||||
|
if (interfaceModule) {
|
||||||
|
duplicateDoc(builtinTypeDecl.attributes(), repairs);
|
||||||
|
duplicateNamed(builtinTypeDecl.attributes(), "BuiltinType", repairs);
|
||||||
|
for (final PbsAst.FunctionSignature signature : builtinTypeDecl.signatures()) {
|
||||||
|
duplicateDoc(signature.attributes(), repairs);
|
||||||
|
duplicateNamed(signature.attributes(), "IntrinsicCall", repairs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case PbsAst.ErrorDecl errorDecl -> duplicateDoc(errorDecl.attributes(), repairs);
|
||||||
|
case PbsAst.EnumDecl enumDecl -> duplicateDoc(enumDecl.attributes(), repairs);
|
||||||
|
case PbsAst.CallbackDecl callbackDecl -> duplicateDoc(callbackDecl.attributes(), repairs);
|
||||||
|
case PbsAst.ConstDecl constDecl -> {
|
||||||
|
duplicateDoc(constDecl.attributes(), repairs);
|
||||||
|
duplicateNamed(constDecl.attributes(), "BuiltinConst", repairs);
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
repairs.sort(Comparator
|
||||||
|
.comparingInt(PbsQuickFix::startOffset)
|
||||||
|
.thenComparingInt(PbsQuickFix::endOffset)
|
||||||
|
.thenComparing(PbsQuickFix::diagnosticCode));
|
||||||
|
return List.copyOf(repairs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void collectHostSignature(
|
||||||
|
final PbsAst.FunctionSignature signature,
|
||||||
|
final List<PbsQuickFix> repairs) {
|
||||||
|
duplicateDoc(signature.attributes(), repairs);
|
||||||
|
duplicateNamed(signature.attributes(), "Host", repairs);
|
||||||
|
duplicateNamed(signature.attributes(), "InitAllowed", repairs);
|
||||||
|
duplicateNamed(signature.attributes(), "AssetLowering", repairs);
|
||||||
|
final List<PbsAst.Attribute> initAllowed = named(signature.attributes(), "InitAllowed");
|
||||||
|
if (!initAllowed.isEmpty() && !initAllowed.getFirst().arguments().isEmpty()) {
|
||||||
|
add(repairs, initAllowed.getFirst(), PbsSemanticsErrors.E_SEM_MALFORMED_RESERVED_ATTRIBUTE.name(),
|
||||||
|
INIT_ALLOWED_REPLACEMENT, REMOVE_INIT_ALLOWED_ARGUMENTS_TITLE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void duplicateDoc(
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
|
final List<PbsQuickFix> repairs) {
|
||||||
|
duplicateNamed(attributes, "Doc", repairs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void duplicateNamed(
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
|
final String name,
|
||||||
|
final List<PbsQuickFix> repairs) {
|
||||||
|
final List<PbsAst.Attribute> matches = named(attributes, name);
|
||||||
|
for (int index = 1; index < matches.size(); index++) {
|
||||||
|
add(repairs, matches.get(index), PbsSemanticsErrors.E_SEM_DUPLICATE_RESERVED_ATTRIBUTE.name(),
|
||||||
|
"", REMOVE_DUPLICATE_TITLE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<PbsAst.Attribute> named(
|
||||||
|
final ReadOnlyList<PbsAst.Attribute> attributes,
|
||||||
|
final String name) {
|
||||||
|
final ArrayList<PbsAst.Attribute> matches = new ArrayList<>();
|
||||||
|
if (attributes == null) {
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
for (final PbsAst.Attribute attribute : attributes) {
|
||||||
|
if (name.equals(attribute.name())) {
|
||||||
|
matches.add(attribute);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void add(
|
||||||
|
final List<PbsQuickFix> repairs,
|
||||||
|
final PbsAst.Attribute attribute,
|
||||||
|
final String code,
|
||||||
|
final String newText,
|
||||||
|
final String title) {
|
||||||
|
if (attribute == null || attribute.span() == null || attribute.span().isNone()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final Span span = attribute.span();
|
||||||
|
final long start = span.getStart();
|
||||||
|
final long end = span.getEnd();
|
||||||
|
if (start < 0 || end < start || end > Integer.MAX_VALUE) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
repairs.add(new PbsQuickFix(code, (int) start, (int) end, newText, title));
|
||||||
|
}
|
||||||
|
}
|
||||||
+73
@@ -5,9 +5,15 @@ import p.studio.utilities.structures.ReadOnlyList;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
import java.net.JarURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.jar.JarEntry;
|
||||||
|
|
||||||
public final class ResourceStdlibEnvironmentResolver implements StdlibEnvironmentResolver {
|
public final class ResourceStdlibEnvironmentResolver implements StdlibEnvironmentResolver {
|
||||||
private static final String STDLIB_ROOT = "stdlib";
|
private static final String STDLIB_ROOT = "stdlib";
|
||||||
@@ -37,6 +43,73 @@ public final class ResourceStdlibEnvironmentResolver implements StdlibEnvironmen
|
|||||||
barrelSource.get()));
|
barrelSource.get()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ReadOnlyList<StdlibModuleSource> modules() {
|
||||||
|
final String root = target.exportReferenceName().toLowerCase()
|
||||||
|
+ "/" + STDLIB_ROOT + "/" + stdlibVersion;
|
||||||
|
final ClassLoader classLoader = ResourceStdlibEnvironmentResolver.class.getClassLoader();
|
||||||
|
if (classLoader == null) {
|
||||||
|
return ReadOnlyList.empty();
|
||||||
|
}
|
||||||
|
final URL url = classLoader.getResource(root);
|
||||||
|
if (url == null) {
|
||||||
|
return ReadOnlyList.empty();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final List<List<String>> modulePaths = "jar".equals(url.getProtocol())
|
||||||
|
? jarModulePaths(url, root)
|
||||||
|
: fileModulePaths(url);
|
||||||
|
final ArrayList<StdlibModuleSource> modules = new ArrayList<>();
|
||||||
|
for (final List<String> modulePath : modulePaths) {
|
||||||
|
if (modulePath.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final String project = modulePath.getFirst();
|
||||||
|
final ReadOnlyList<String> segments = ReadOnlyList.wrap(modulePath.subList(1, modulePath.size()));
|
||||||
|
resolveModule(project, segments).ifPresent(modules::add);
|
||||||
|
}
|
||||||
|
return ReadOnlyList.wrap(modules);
|
||||||
|
} catch (final Exception ignored) {
|
||||||
|
return ReadOnlyList.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<List<String>> fileModulePaths(final URL url) throws Exception {
|
||||||
|
final Path rootPath = Path.of(url.toURI());
|
||||||
|
final ArrayList<List<String>> modulePaths = new ArrayList<>();
|
||||||
|
try (var walk = Files.walk(rootPath)) {
|
||||||
|
walk.filter(path -> "main.pbs".equals(String.valueOf(path.getFileName()))
|
||||||
|
&& Files.isRegularFile(path.getParent().resolve("mod.barrel")))
|
||||||
|
.forEach(path -> modulePaths.add(segments(rootPath.relativize(path.getParent()))));
|
||||||
|
}
|
||||||
|
return modulePaths;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<List<String>> jarModulePaths(final URL url, final String root) throws IOException {
|
||||||
|
final JarURLConnection connection = (JarURLConnection) url.openConnection();
|
||||||
|
final var jarFile = connection.getJarFile();
|
||||||
|
final String prefix = root + "/";
|
||||||
|
final ArrayList<List<String>> modulePaths = new ArrayList<>();
|
||||||
|
jarFile.stream()
|
||||||
|
.map(JarEntry::getName)
|
||||||
|
.filter(name -> name.startsWith(prefix) && name.endsWith("/main.pbs"))
|
||||||
|
.forEach(name -> {
|
||||||
|
final String directory = name.substring(prefix.length(), name.length() - "/main.pbs".length());
|
||||||
|
if (!directory.isBlank() && jarFile.getEntry(prefix + directory + "/mod.barrel") != null) {
|
||||||
|
modulePaths.add(List.of(directory.split("/")));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return modulePaths;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> segments(final Path relative) {
|
||||||
|
final ArrayList<String> segments = new ArrayList<>();
|
||||||
|
for (final Path segment : relative) {
|
||||||
|
segments.add(segment.toString());
|
||||||
|
}
|
||||||
|
return segments;
|
||||||
|
}
|
||||||
|
|
||||||
private String moduleBasePath(
|
private String moduleBasePath(
|
||||||
final String project,
|
final String project,
|
||||||
final ReadOnlyList<String> pathSegments) {
|
final ReadOnlyList<String> pathSegments) {
|
||||||
|
|||||||
+4
@@ -6,5 +6,9 @@ import java.util.Optional;
|
|||||||
|
|
||||||
public interface StdlibEnvironment {
|
public interface StdlibEnvironment {
|
||||||
Optional<StdlibModuleSource> resolveModule(String project, ReadOnlyList<String> pathSegments);
|
Optional<StdlibModuleSource> resolveModule(String project, ReadOnlyList<String> pathSegments);
|
||||||
|
|
||||||
|
default ReadOnlyList<StdlibModuleSource> modules() {
|
||||||
|
return ReadOnlyList.empty();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+122
-426
@@ -5,27 +5,22 @@ import p.studio.compiler.messages.BuildingIssueSink;
|
|||||||
import p.studio.compiler.messages.FESurfaceContext;
|
import p.studio.compiler.messages.FESurfaceContext;
|
||||||
import p.studio.compiler.messages.FrontendPhaseContext;
|
import p.studio.compiler.messages.FrontendPhaseContext;
|
||||||
import p.studio.compiler.models.IRBackend;
|
import p.studio.compiler.models.IRBackend;
|
||||||
import p.studio.compiler.models.IRBackendExecutableFunction;
|
import p.studio.compiler.models.SourceKind;
|
||||||
import p.studio.compiler.models.IRGlobal;
|
|
||||||
import p.studio.compiler.models.IRGlobalOrigin;
|
|
||||||
import p.studio.compiler.models.IRGlobalVisibility;
|
|
||||||
import p.studio.compiler.models.IRHiddenGlobalKind;
|
|
||||||
import p.studio.compiler.models.IRSyntheticCallableKind;
|
|
||||||
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
||||||
import p.studio.compiler.pbs.PbsReservedMetadataExtractor;
|
import p.studio.compiler.pbs.PbsReservedMetadataExtractor;
|
||||||
import p.studio.compiler.pbs.semantics.PbsFlowSemanticsValidator;
|
import p.studio.compiler.pbs.semantics.PbsFlowSemanticsValidator;
|
||||||
import p.studio.compiler.pbs.stdlib.InterfaceModuleLoader;
|
import p.studio.compiler.pbs.stdlib.InterfaceModuleLoader;
|
||||||
import p.studio.compiler.pbs.stdlib.ResourceStdlibEnvironmentResolver;
|
import p.studio.compiler.pbs.stdlib.ResourceStdlibEnvironmentResolver;
|
||||||
import p.studio.compiler.pbs.stdlib.StdlibEnvironmentResolver;
|
import p.studio.compiler.pbs.stdlib.StdlibEnvironmentResolver;
|
||||||
import p.studio.compiler.source.Span;
|
|
||||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||||
import p.studio.compiler.source.identifiers.CallableId;
|
|
||||||
import p.studio.compiler.source.identifiers.FileId;
|
import p.studio.compiler.source.identifiers.FileId;
|
||||||
import p.studio.compiler.source.identifiers.ModuleId;
|
import p.studio.compiler.source.identifiers.ModuleId;
|
||||||
import p.studio.compiler.source.tables.CallableSignatureRef;
|
import p.studio.compiler.source.tables.ModuleReference;
|
||||||
import p.studio.utilities.logs.LogAggregator;
|
import p.studio.utilities.logs.LogAggregator;
|
||||||
import p.studio.utilities.structures.ReadOnlyList;
|
import p.studio.utilities.structures.ReadOnlyList;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -136,11 +131,15 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
|||||||
final Map<FileId, p.studio.compiler.pbs.ast.PbsAst.File> astByFile = new LinkedHashMap<>();
|
final Map<FileId, p.studio.compiler.pbs.ast.PbsAst.File> astByFile = new LinkedHashMap<>();
|
||||||
final Map<FileId, ReadOnlyList<p.studio.compiler.pbs.ast.PbsAst.TopDecl>> supplementalTopDeclsByFile = new LinkedHashMap<>();
|
final Map<FileId, ReadOnlyList<p.studio.compiler.pbs.ast.PbsAst.TopDecl>> supplementalTopDeclsByFile = new LinkedHashMap<>();
|
||||||
final Map<FileId, ReadOnlyList<PbsInlineHintSurface>> inlineHintsByFile = new LinkedHashMap<>();
|
final Map<FileId, ReadOnlyList<PbsInlineHintSurface>> inlineHintsByFile = new LinkedHashMap<>();
|
||||||
|
final Map<FileId, SourceKind> sourceKindByFile = new LinkedHashMap<>();
|
||||||
for (final var entry : importedSemanticContexts.entrySet()) {
|
for (final var entry : importedSemanticContexts.entrySet()) {
|
||||||
supplementalTopDeclsByFile.put(entry.getKey(), entry.getValue().supplementalTopDecls());
|
supplementalTopDeclsByFile.put(entry.getKey(), entry.getValue().supplementalTopDecls());
|
||||||
}
|
}
|
||||||
for (final var parsedSourceFile : assembly.parsedSourceFiles()) {
|
for (final var parsedSourceFile : assembly.parsedSourceFiles()) {
|
||||||
astByFile.put(parsedSourceFile.fileId(), parsedSourceFile.ast());
|
astByFile.put(parsedSourceFile.fileId(), parsedSourceFile.ast());
|
||||||
|
sourceKindByFile.put(
|
||||||
|
parsedSourceFile.fileId(),
|
||||||
|
parsedSourceFile.sourceKind() == null ? SourceKind.PROJECT : parsedSourceFile.sourceKind());
|
||||||
final var importedSemanticContext = importedSemanticContexts.getOrDefault(
|
final var importedSemanticContext = importedSemanticContexts.getOrDefault(
|
||||||
parsedSourceFile.fileId(),
|
parsedSourceFile.fileId(),
|
||||||
PbsImportedSemanticContext.empty());
|
PbsImportedSemanticContext.empty());
|
||||||
@@ -153,22 +152,87 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
|||||||
inlineHintsByFile.put(parsedSourceFile.fileId(), inlineHints);
|
inlineHintsByFile.put(parsedSourceFile.fileId(), inlineHints);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
final Map<ModuleReference, Path> physicalModuleFiles = physicalModuleFiles(ctx, assembly);
|
||||||
return new PbsSemanticReadSurface(
|
return new PbsSemanticReadSurface(
|
||||||
Map.copyOf(astByFile),
|
Map.copyOf(astByFile),
|
||||||
Map.copyOf(supplementalTopDeclsByFile),
|
Map.copyOf(supplementalTopDeclsByFile),
|
||||||
Map.copyOf(inlineHintsByFile));
|
Map.copyOf(inlineHintsByFile),
|
||||||
|
Map.copyOf(sourceKindByFile),
|
||||||
|
physicalModuleFiles,
|
||||||
|
moduleCompletionLabels(ctx, physicalModuleFiles));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<ModuleReference, Path> physicalModuleFiles(
|
||||||
|
final FrontendPhaseContext ctx,
|
||||||
|
final PbsModuleAssembly assembly) {
|
||||||
|
final Map<ModuleReference, Path> files = new LinkedHashMap<>();
|
||||||
|
if (ctx == null || ctx.fileTable == null || assembly == null || assembly.parsedSourceFiles() == null) {
|
||||||
|
return Map.of();
|
||||||
|
}
|
||||||
|
for (final PbsParsedSourceFile parsed : assembly.parsedSourceFiles()) {
|
||||||
|
if (parsed.fileId() == null || parsed.fileId().isNone()
|
||||||
|
|| parsed.moduleId() == null || parsed.moduleId().isNone()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final var handle = ctx.fileTable.get(parsed.fileId());
|
||||||
|
if (handle == null || handle.getCanonPath() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final Path path = handle.getCanonPath().toAbsolutePath().normalize();
|
||||||
|
if (!Files.isRegularFile(path)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final ModuleReference reference = assembly.moduleTable().get(parsed.moduleId());
|
||||||
|
if (reference == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
files.merge(reference, path, (left, right) ->
|
||||||
|
left.toString().compareTo(right.toString()) <= 0 ? left : right);
|
||||||
|
}
|
||||||
|
return Map.copyOf(files);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> moduleCompletionLabels(
|
||||||
|
final FrontendPhaseContext ctx,
|
||||||
|
final Map<ModuleReference, Path> physicalModuleFiles) {
|
||||||
|
final var labels = new java.util.TreeSet<String>();
|
||||||
|
for (final ModuleReference reference : physicalModuleFiles.keySet()) {
|
||||||
|
labels.add(moduleLabel(reference.project(), reference.pathSegments()));
|
||||||
|
}
|
||||||
|
if (ctx != null) {
|
||||||
|
final var environment = new ResourceStdlibEnvironmentResolver().resolve(ctx.stdlibVersion(), ctx.target());
|
||||||
|
for (final var module : environment.modules()) {
|
||||||
|
labels.add(moduleLabel(module.project(), module.pathSegments()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return List.copyOf(labels);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String moduleLabel(
|
||||||
|
final String project,
|
||||||
|
final ReadOnlyList<String> pathSegments) {
|
||||||
|
if (project == null || project.isBlank()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (pathSegments == null || pathSegments.isEmpty()) {
|
||||||
|
return "@" + project;
|
||||||
|
}
|
||||||
|
return "@" + project + ":" + String.join("/", pathSegments.asList());
|
||||||
}
|
}
|
||||||
|
|
||||||
public record PbsSemanticReadSurface(
|
public record PbsSemanticReadSurface(
|
||||||
Map<FileId, p.studio.compiler.pbs.ast.PbsAst.File> astByFile,
|
Map<FileId, p.studio.compiler.pbs.ast.PbsAst.File> astByFile,
|
||||||
Map<FileId, ReadOnlyList<p.studio.compiler.pbs.ast.PbsAst.TopDecl>> supplementalTopDeclsByFile,
|
Map<FileId, ReadOnlyList<p.studio.compiler.pbs.ast.PbsAst.TopDecl>> supplementalTopDeclsByFile,
|
||||||
Map<FileId, ReadOnlyList<PbsInlineHintSurface>> inlineHintsByFile) {
|
Map<FileId, ReadOnlyList<PbsInlineHintSurface>> inlineHintsByFile,
|
||||||
|
Map<FileId, SourceKind> sourceKindByFile,
|
||||||
|
Map<ModuleReference, Path> physicalModuleFileByReference,
|
||||||
|
List<String> moduleCompletionLabels) {
|
||||||
}
|
}
|
||||||
|
|
||||||
private IRBackend mergeCompiledSources(
|
private IRBackend mergeCompiledSources(
|
||||||
final ArrayList<CompiledSourceFile> compiledSourceFiles,
|
final ArrayList<CompiledSourceFile> compiledSourceFiles,
|
||||||
final Set<ModuleId> failedModuleIds,
|
final Set<ModuleId> failedModuleIds,
|
||||||
final Map<ModuleId, Set<ModuleId>> moduleDependencyGraph) {
|
final Map<ModuleId, ReadOnlyList<ModuleId>> moduleDependencyGraph) {
|
||||||
final var irBackendAggregator = IRBackend.aggregator();
|
final var irBackendAggregator = IRBackend.aggregator();
|
||||||
final var blockedModuleIds = blockedModulesByDependency(failedModuleIds, moduleDependencyGraph);
|
final var blockedModuleIds = blockedModulesByDependency(failedModuleIds, moduleDependencyGraph);
|
||||||
|
|
||||||
@@ -178,438 +242,70 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
|||||||
}
|
}
|
||||||
irBackendAggregator.merge(compiledSource.irBackendFile());
|
irBackendAggregator.merge(compiledSource.irBackendFile());
|
||||||
}
|
}
|
||||||
return synthesizePublishedLifecycle(irBackendAggregator.emit());
|
irBackendAggregator.lifecycleModuleOrder(lifecycleModuleOrder(
|
||||||
|
compiledSourceFiles,
|
||||||
|
blockedModuleIds,
|
||||||
|
moduleDependencyGraph));
|
||||||
|
return irBackendAggregator.emit();
|
||||||
}
|
}
|
||||||
|
|
||||||
private IRBackend synthesizePublishedLifecycle(final IRBackend baseBackend) {
|
private ReadOnlyList<ModuleId> lifecycleModuleOrder(
|
||||||
final var callableSignatures = new ArrayList<>(baseBackend.getCallableSignatures().asList());
|
final ArrayList<CompiledSourceFile> compiledSourceFiles,
|
||||||
final var executableFunctions = new ArrayList<>(baseBackend.getExecutableFunctions().asList());
|
final Set<ModuleId> blockedModuleIds,
|
||||||
final var globals = new ArrayList<>(baseBackend.getGlobals().asList());
|
final Map<ModuleId, ReadOnlyList<ModuleId>> dependenciesByModule) {
|
||||||
final var fileInitFunctionsByModule = new LinkedHashMap<ModuleId, List<IRBackendExecutableFunction>>();
|
final var availableModules = new LinkedHashSet<ModuleId>();
|
||||||
final var projectInitAnchorsByModule = new LinkedHashMap<ModuleId, String>();
|
for (final var compiledSource : compiledSourceFiles) {
|
||||||
final var wrapperNamesByModule = new LinkedHashMap<ModuleId, String>();
|
if (!blockedModuleIds.contains(compiledSource.moduleId())) {
|
||||||
final var frameAnchorsByModule = new LinkedHashMap<ModuleId, String>();
|
availableModules.add(compiledSource.moduleId());
|
||||||
|
|
||||||
for (final var executable : executableFunctions) {
|
|
||||||
if (!executable.callableName().startsWith("__pbs.file_init$")) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
fileInitFunctionsByModule
|
|
||||||
.computeIfAbsent(normalizeModuleId(executable.moduleId()), ignored -> new ArrayList<>())
|
|
||||||
.add(executable);
|
|
||||||
}
|
|
||||||
for (final var syntheticFunction : baseBackend.getSyntheticFunctions()) {
|
|
||||||
final var moduleId = normalizeModuleId(syntheticFunction.moduleId());
|
|
||||||
switch (syntheticFunction.kind()) {
|
|
||||||
case PROJECT_INIT -> projectInitAnchorsByModule.put(moduleId, syntheticFunction.origin().anchorCallableName());
|
|
||||||
case PUBLISHED_FRAME_WRAPPER -> {
|
|
||||||
wrapperNamesByModule.put(moduleId, syntheticFunction.callableName());
|
|
||||||
frameAnchorsByModule.put(moduleId, syntheticFunction.origin().anchorCallableName());
|
|
||||||
}
|
|
||||||
default -> {
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final ModuleId entryPointModuleId;
|
final var ordered = new ArrayList<ModuleId>(availableModules.size());
|
||||||
final String entryPointCallableName;
|
final var visiting = new HashSet<ModuleId>();
|
||||||
if (wrapperNamesByModule.size() == 1) {
|
final var visited = new HashSet<ModuleId>();
|
||||||
entryPointModuleId = wrapperNamesByModule.keySet().iterator().next();
|
for (final var moduleId : availableModules) {
|
||||||
entryPointCallableName = wrapperNamesByModule.get(entryPointModuleId);
|
appendDependenciesFirst(
|
||||||
} else {
|
|
||||||
entryPointModuleId = baseBackend.getEntryPointModuleId();
|
|
||||||
entryPointCallableName = baseBackend.getEntryPointCallableName();
|
|
||||||
}
|
|
||||||
|
|
||||||
final var sortedModuleIds = new ArrayList<ModuleId>();
|
|
||||||
sortedModuleIds.addAll(fileInitFunctionsByModule.keySet());
|
|
||||||
for (final var moduleId : wrapperNamesByModule.keySet()) {
|
|
||||||
if (!sortedModuleIds.contains(moduleId)) {
|
|
||||||
sortedModuleIds.add(moduleId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sortedModuleIds.sort(Comparator.comparing(moduleId -> moduleSortKey(baseBackend, moduleId)));
|
|
||||||
|
|
||||||
final var moduleInitCallableIds = new LinkedHashMap<ModuleId, CallableId>();
|
|
||||||
for (final var moduleId : sortedModuleIds) {
|
|
||||||
final var moduleInitName = PbsFrontendCompiler.moduleInitCallableName(moduleId);
|
|
||||||
final var fileInitFunctions = new ArrayList<>(fileInitFunctionsByModule.getOrDefault(moduleId, List.of()));
|
|
||||||
if (fileInitFunctions.isEmpty()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
fileInitFunctions.sort(Comparator.comparingInt(fn -> fn.fileId().getId()));
|
|
||||||
|
|
||||||
final var callableId = new CallableId(callableSignatures.size());
|
|
||||||
callableSignatures.add(new CallableSignatureRef(moduleId, moduleInitName, 0, "() -> unit"));
|
|
||||||
moduleInitCallableIds.put(moduleId, callableId);
|
|
||||||
|
|
||||||
final var instructions = new ArrayList<IRBackendExecutableFunction.Instruction>();
|
|
||||||
var anchorSpan = fileInitFunctions.getFirst().span();
|
|
||||||
var anchorFileId = fileInitFunctions.getFirst().fileId();
|
|
||||||
for (final var fileInitFunction : fileInitFunctions) {
|
|
||||||
instructions.add(callInstruction(fileInitFunction, fileInitFunction.span()));
|
|
||||||
anchorSpan = fileInitFunction.span();
|
|
||||||
anchorFileId = fileInitFunction.fileId();
|
|
||||||
}
|
|
||||||
instructions.add(retInstruction(anchorSpan));
|
|
||||||
executableFunctions.add(new IRBackendExecutableFunction(
|
|
||||||
anchorFileId,
|
|
||||||
moduleId,
|
moduleId,
|
||||||
moduleInitName,
|
availableModules,
|
||||||
callableId,
|
dependenciesByModule,
|
||||||
safeToInt(anchorSpan.getStart()),
|
visiting,
|
||||||
safeToInt(anchorSpan.getEnd()),
|
visited,
|
||||||
0,
|
ordered);
|
||||||
0,
|
|
||||||
0,
|
|
||||||
1,
|
|
||||||
ReadOnlyList.wrap(instructions),
|
|
||||||
anchorSpan));
|
|
||||||
}
|
}
|
||||||
|
return ReadOnlyList.wrap(ordered);
|
||||||
CallableId projectInitCallableId = null;
|
|
||||||
if (!entryPointModuleId.isNone()) {
|
|
||||||
final var projectInitAnchor = projectInitAnchorsByModule.get(entryPointModuleId);
|
|
||||||
final var projectInitTarget = resolveExecutable(executableFunctions, entryPointModuleId, projectInitAnchor);
|
|
||||||
if (projectInitTarget != null) {
|
|
||||||
final var projectInitName = PbsFrontendCompiler.projectInitCallableName(entryPointModuleId);
|
|
||||||
projectInitCallableId = new CallableId(callableSignatures.size());
|
|
||||||
callableSignatures.add(new CallableSignatureRef(entryPointModuleId, projectInitName, 0, "() -> unit"));
|
|
||||||
executableFunctions.add(new IRBackendExecutableFunction(
|
|
||||||
projectInitTarget.fileId(),
|
|
||||||
entryPointModuleId,
|
|
||||||
projectInitName,
|
|
||||||
projectInitCallableId,
|
|
||||||
projectInitTarget.sourceStart(),
|
|
||||||
projectInitTarget.sourceEnd(),
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
1,
|
|
||||||
ReadOnlyList.from(
|
|
||||||
callInstruction(projectInitTarget, projectInitTarget.span()),
|
|
||||||
retInstruction(projectInitTarget.span())),
|
|
||||||
projectInitTarget.span()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final var frameExecutable = resolveExecutable(
|
|
||||||
executableFunctions,
|
|
||||||
entryPointModuleId,
|
|
||||||
frameAnchorsByModule.get(entryPointModuleId));
|
|
||||||
if (frameExecutable != null
|
|
||||||
&& entryPointCallableName != null
|
|
||||||
&& !entryPointCallableName.isBlank()
|
|
||||||
&& !entryPointModuleId.isNone()) {
|
|
||||||
final var existingBootGuard = globals.stream()
|
|
||||||
.filter(global -> moduleIdsMatch(entryPointModuleId, global.moduleId()))
|
|
||||||
.filter(global -> global.hiddenKind() == IRHiddenGlobalKind.BOOT_GUARD)
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
final var bootGuardSlot = existingBootGuard != null
|
|
||||||
? existingBootGuard.slot()
|
|
||||||
: nextGlobalSlot(globals, entryPointModuleId);
|
|
||||||
final var wrapperCallableId = new CallableId(callableSignatures.size());
|
|
||||||
callableSignatures.add(new CallableSignatureRef(entryPointModuleId, entryPointCallableName, 0, "() -> unit"));
|
|
||||||
final var instructions = new ArrayList<IRBackendExecutableFunction.Instruction>();
|
|
||||||
instructions.add(getGlobalInstruction(bootGuardSlot, frameExecutable.span()));
|
|
||||||
instructions.add(pushBoolInstruction(true, frameExecutable.span()));
|
|
||||||
instructions.add(eqInstruction(frameExecutable.span()));
|
|
||||||
instructions.add(jumpIfTrueInstruction("bootstrap_done", frameExecutable.span()));
|
|
||||||
for (final var moduleId : sortedModuleIds) {
|
|
||||||
final var moduleInitCallableId = moduleInitCallableIds.get(moduleId);
|
|
||||||
if (moduleInitCallableId == null) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
instructions.add(new IRBackendExecutableFunction.Instruction(
|
|
||||||
IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
|
||||||
moduleId,
|
|
||||||
PbsFrontendCompiler.moduleInitCallableName(moduleId),
|
|
||||||
moduleInitCallableId,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
frameExecutable.span()));
|
|
||||||
}
|
|
||||||
if (projectInitCallableId != null) {
|
|
||||||
instructions.add(new IRBackendExecutableFunction.Instruction(
|
|
||||||
IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
|
||||||
entryPointModuleId,
|
|
||||||
PbsFrontendCompiler.projectInitCallableName(entryPointModuleId),
|
|
||||||
projectInitCallableId,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
frameExecutable.span()));
|
|
||||||
}
|
|
||||||
instructions.add(pushBoolInstruction(true, frameExecutable.span()));
|
|
||||||
instructions.add(setGlobalInstruction(bootGuardSlot, frameExecutable.span()));
|
|
||||||
instructions.add(labelInstruction("bootstrap_done", frameExecutable.span()));
|
|
||||||
instructions.add(callInstruction(frameExecutable, frameExecutable.span()));
|
|
||||||
instructions.add(retInstruction(frameExecutable.span()));
|
|
||||||
executableFunctions.add(new IRBackendExecutableFunction(
|
|
||||||
frameExecutable.fileId(),
|
|
||||||
entryPointModuleId,
|
|
||||||
entryPointCallableName,
|
|
||||||
wrapperCallableId,
|
|
||||||
frameExecutable.sourceStart(),
|
|
||||||
frameExecutable.sourceEnd(),
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
2,
|
|
||||||
ReadOnlyList.wrap(instructions),
|
|
||||||
frameExecutable.span()));
|
|
||||||
|
|
||||||
if (existingBootGuard == null) {
|
|
||||||
globals.add(new IRGlobal(
|
|
||||||
frameExecutable.fileId(),
|
|
||||||
entryPointModuleId,
|
|
||||||
PbsFrontendCompiler.bootGuardGlobalName(entryPointModuleId),
|
|
||||||
"bool",
|
|
||||||
bootGuardSlot,
|
|
||||||
IRGlobalVisibility.MODULE,
|
|
||||||
true,
|
|
||||||
IRHiddenGlobalKind.BOOT_GUARD,
|
|
||||||
new IRGlobalOrigin(
|
|
||||||
frameExecutable.fileId(),
|
|
||||||
entryPointModuleId,
|
|
||||||
frameAnchorsByModule.getOrDefault(entryPointModuleId, frameExecutable.callableName()),
|
|
||||||
frameExecutable.span(),
|
|
||||||
"BOOT_GUARD"),
|
|
||||||
frameExecutable.span()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final var normalizedGlobals = normalizeGlobalSlots(globals);
|
|
||||||
|
|
||||||
return IRBackend.builder()
|
|
||||||
.entryPointCallableName(entryPointCallableName)
|
|
||||||
.entryPointModuleId(entryPointModuleId)
|
|
||||||
.functions(baseBackend.getFunctions())
|
|
||||||
.syntheticFunctions(baseBackend.getSyntheticFunctions())
|
|
||||||
.globals(ReadOnlyList.wrap(normalizedGlobals))
|
|
||||||
.executableFunctions(ReadOnlyList.wrap(executableFunctions))
|
|
||||||
.modulePool(baseBackend.getModulePool())
|
|
||||||
.callableSignatures(ReadOnlyList.wrap(callableSignatures))
|
|
||||||
.intrinsicPool(baseBackend.getIntrinsicPool())
|
|
||||||
.reservedMetadata(baseBackend.getReservedMetadata())
|
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int nextGlobalSlot(
|
private void appendDependenciesFirst(
|
||||||
final ArrayList<IRGlobal> globals,
|
|
||||||
final ModuleId moduleId) {
|
|
||||||
var nextSlot = 0;
|
|
||||||
for (final var global : globals) {
|
|
||||||
if (!moduleIdsMatch(moduleId, global.moduleId())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
nextSlot = Math.max(nextSlot, global.slot() + 1);
|
|
||||||
}
|
|
||||||
return nextSlot;
|
|
||||||
}
|
|
||||||
|
|
||||||
private ArrayList<IRGlobal> normalizeGlobalSlots(final ArrayList<IRGlobal> globals) {
|
|
||||||
final var nextSlotByModule = new LinkedHashMap<ModuleId, Integer>();
|
|
||||||
final var normalized = new ArrayList<IRGlobal>(globals.size());
|
|
||||||
for (final var global : globals) {
|
|
||||||
final var moduleId = normalizeModuleId(global.moduleId());
|
|
||||||
final var slot = nextSlotByModule.getOrDefault(moduleId, 0);
|
|
||||||
nextSlotByModule.put(moduleId, slot + 1);
|
|
||||||
normalized.add(new IRGlobal(
|
|
||||||
global.fileId(),
|
|
||||||
moduleId,
|
|
||||||
global.name(),
|
|
||||||
global.declaredTypeSurface(),
|
|
||||||
slot,
|
|
||||||
global.visibility(),
|
|
||||||
global.isHidden(),
|
|
||||||
global.hiddenKind(),
|
|
||||||
global.origin(),
|
|
||||||
global.span()));
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
private IRBackendExecutableFunction resolveExecutable(
|
|
||||||
final ArrayList<IRBackendExecutableFunction> executableFunctions,
|
|
||||||
final ModuleId moduleId,
|
final ModuleId moduleId,
|
||||||
final String callableName) {
|
final Set<ModuleId> availableModules,
|
||||||
if (callableName == null || callableName.isBlank()) {
|
final Map<ModuleId, ReadOnlyList<ModuleId>> dependenciesByModule,
|
||||||
return null;
|
final Set<ModuleId> visiting,
|
||||||
|
final Set<ModuleId> visited,
|
||||||
|
final ArrayList<ModuleId> ordered) {
|
||||||
|
if (visited.contains(moduleId) || !availableModules.contains(moduleId)) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
for (final var executable : executableFunctions) {
|
if (!visiting.add(moduleId)) {
|
||||||
if (!callableName.equals(executable.callableName())) {
|
return;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!moduleIdsMatch(moduleId, executable.moduleId())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
return executable;
|
|
||||||
}
|
}
|
||||||
return null;
|
for (final var dependency : dependenciesByModule.getOrDefault(moduleId, ReadOnlyList.empty())) {
|
||||||
}
|
appendDependenciesFirst(
|
||||||
|
dependency,
|
||||||
private IRBackendExecutableFunction.Instruction callInstruction(
|
availableModules,
|
||||||
final IRBackendExecutableFunction callee,
|
dependenciesByModule,
|
||||||
final Span span) {
|
visiting,
|
||||||
return new IRBackendExecutableFunction.Instruction(
|
visited,
|
||||||
IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
ordered);
|
||||||
callee.moduleId(),
|
|
||||||
callee.callableName(),
|
|
||||||
callee.callableId(),
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
callee.paramSlots(),
|
|
||||||
callee.returnSlots(),
|
|
||||||
span);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IRBackendExecutableFunction.Instruction retInstruction(final Span span) {
|
|
||||||
return new IRBackendExecutableFunction.Instruction(
|
|
||||||
IRBackendExecutableFunction.InstructionKind.RET,
|
|
||||||
"",
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
span);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IRBackendExecutableFunction.Instruction getGlobalInstruction(
|
|
||||||
final int slot,
|
|
||||||
final Span span) {
|
|
||||||
return new IRBackendExecutableFunction.Instruction(
|
|
||||||
IRBackendExecutableFunction.InstructionKind.GET_GLOBAL,
|
|
||||||
"",
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
slot,
|
|
||||||
null,
|
|
||||||
span);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IRBackendExecutableFunction.Instruction setGlobalInstruction(
|
|
||||||
final int slot,
|
|
||||||
final Span span) {
|
|
||||||
return new IRBackendExecutableFunction.Instruction(
|
|
||||||
IRBackendExecutableFunction.InstructionKind.SET_GLOBAL,
|
|
||||||
"",
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
slot,
|
|
||||||
null,
|
|
||||||
span);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IRBackendExecutableFunction.Instruction pushBoolInstruction(
|
|
||||||
final boolean value,
|
|
||||||
final Span span) {
|
|
||||||
return new IRBackendExecutableFunction.Instruction(
|
|
||||||
IRBackendExecutableFunction.InstructionKind.PUSH_BOOL,
|
|
||||||
"",
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
value ? "true" : "false",
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
span);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IRBackendExecutableFunction.Instruction eqInstruction(final Span span) {
|
|
||||||
return new IRBackendExecutableFunction.Instruction(
|
|
||||||
IRBackendExecutableFunction.InstructionKind.EQ,
|
|
||||||
"",
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
span);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IRBackendExecutableFunction.Instruction labelInstruction(
|
|
||||||
final String label,
|
|
||||||
final Span span) {
|
|
||||||
return new IRBackendExecutableFunction.Instruction(
|
|
||||||
IRBackendExecutableFunction.InstructionKind.LABEL,
|
|
||||||
"",
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
label,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
span);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IRBackendExecutableFunction.Instruction jumpIfTrueInstruction(
|
|
||||||
final String targetLabel,
|
|
||||||
final Span span) {
|
|
||||||
return new IRBackendExecutableFunction.Instruction(
|
|
||||||
IRBackendExecutableFunction.InstructionKind.JMP_IF_TRUE,
|
|
||||||
"",
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
targetLabel,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
span);
|
|
||||||
}
|
|
||||||
|
|
||||||
private ModuleId normalizeModuleId(final ModuleId moduleId) {
|
|
||||||
return moduleId == null ? ModuleId.none() : moduleId;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean moduleIdsMatch(
|
|
||||||
final ModuleId left,
|
|
||||||
final ModuleId right) {
|
|
||||||
final var normalizedLeft = normalizeModuleId(left);
|
|
||||||
final var normalizedRight = normalizeModuleId(right);
|
|
||||||
if (normalizedLeft.isNone() && normalizedRight.isNone()) {
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
return !normalizedLeft.isNone()
|
visiting.remove(moduleId);
|
||||||
&& !normalizedRight.isNone()
|
if (visited.add(moduleId)) {
|
||||||
&& normalizedLeft.getIndex() == normalizedRight.getIndex();
|
ordered.add(moduleId);
|
||||||
}
|
|
||||||
|
|
||||||
private String moduleSortKey(
|
|
||||||
final IRBackend backend,
|
|
||||||
final ModuleId moduleId) {
|
|
||||||
if (moduleId != null && !moduleId.isNone()) {
|
|
||||||
final var index = moduleId.getIndex();
|
|
||||||
if (index >= 0 && index < backend.getModulePool().size()) {
|
|
||||||
final var moduleReference = backend.getModulePool().get(index);
|
|
||||||
final var joiner = new StringJoiner("/", moduleReference.project() + ":", "");
|
|
||||||
for (final var segment : moduleReference.pathSegments()) {
|
|
||||||
joiner.add(segment);
|
|
||||||
}
|
|
||||||
return joiner.toString();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
private int safeToInt(final long value) {
|
|
||||||
if (value > Integer.MAX_VALUE) {
|
|
||||||
return Integer.MAX_VALUE;
|
|
||||||
}
|
|
||||||
if (value < Integer.MIN_VALUE) {
|
|
||||||
return Integer.MIN_VALUE;
|
|
||||||
}
|
|
||||||
return (int) value;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Set<ModuleId> blockedModulesByDependency(
|
private Set<ModuleId> blockedModulesByDependency(
|
||||||
final Set<ModuleId> failedModuleIds,
|
final Set<ModuleId> failedModuleIds,
|
||||||
final Map<ModuleId, Set<ModuleId>> dependenciesByModule) {
|
final Map<ModuleId, ReadOnlyList<ModuleId>> dependenciesByModule) {
|
||||||
final Map<ModuleId, Set<ModuleId>> dependentsByModule = new HashMap<>();
|
final Map<ModuleId, Set<ModuleId>> dependentsByModule = new HashMap<>();
|
||||||
for (final var entry : dependenciesByModule.entrySet()) {
|
for (final var entry : dependenciesByModule.entrySet()) {
|
||||||
final var importer = entry.getKey();
|
final var importer = entry.getKey();
|
||||||
|
|||||||
+5
-4
@@ -7,13 +7,14 @@ import p.studio.compiler.source.tables.ModuleTable;
|
|||||||
import p.studio.utilities.structures.ReadOnlyList;
|
import p.studio.utilities.structures.ReadOnlyList;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
record PbsModuleAssembly(
|
record PbsModuleAssembly(
|
||||||
ReadOnlyList<PbsParsedSourceFile> parsedSourceFiles,
|
ReadOnlyList<PbsParsedSourceFile> parsedSourceFiles,
|
||||||
Map<ModuleId, Set<ModuleId>> moduleDependencyGraph,
|
Map<ModuleId, ReadOnlyList<ModuleId>> moduleDependencyGraph,
|
||||||
ReadOnlyList<ModuleReference> canonicalModulePool,
|
ReadOnlyList<ModuleReference> canonicalModulePool,
|
||||||
Set<ModuleId> failedModuleIds,
|
Set<ModuleId> failedModuleIds,
|
||||||
ModuleTable moduleTable,
|
ModuleTable moduleTable,
|
||||||
@@ -26,11 +27,11 @@ record PbsModuleAssembly(
|
|||||||
if (moduleDependencyGraph == null || moduleDependencyGraph.isEmpty()) {
|
if (moduleDependencyGraph == null || moduleDependencyGraph.isEmpty()) {
|
||||||
moduleDependencyGraph = Map.of();
|
moduleDependencyGraph = Map.of();
|
||||||
} else {
|
} else {
|
||||||
final var copiedGraph = new HashMap<ModuleId, Set<ModuleId>>();
|
final var copiedGraph = new LinkedHashMap<ModuleId, ReadOnlyList<ModuleId>>();
|
||||||
for (final var entry : moduleDependencyGraph.entrySet()) {
|
for (final var entry : moduleDependencyGraph.entrySet()) {
|
||||||
copiedGraph.put(entry.getKey(), Set.copyOf(entry.getValue() == null ? Set.of() : entry.getValue()));
|
copiedGraph.put(entry.getKey(), entry.getValue() == null ? ReadOnlyList.empty() : entry.getValue());
|
||||||
}
|
}
|
||||||
moduleDependencyGraph = Map.copyOf(copiedGraph);
|
moduleDependencyGraph = java.util.Collections.unmodifiableMap(copiedGraph);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (moduleTable == null) {
|
if (moduleTable == null) {
|
||||||
|
|||||||
+8
-4
@@ -353,20 +353,24 @@ final class PbsModuleAssemblyService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<ModuleId, Set<ModuleId>> buildModuleDependencyGraph(
|
private Map<ModuleId, ReadOnlyList<ModuleId>> buildModuleDependencyGraph(
|
||||||
final ArrayList<PbsParsedSourceFile> parsedSourceFiles,
|
final ArrayList<PbsParsedSourceFile> parsedSourceFiles,
|
||||||
final ModuleTable moduleTable) {
|
final ModuleTable moduleTable) {
|
||||||
final Map<ModuleId, Set<ModuleId>> dependenciesByModule = new HashMap<>();
|
final Map<ModuleId, LinkedHashSet<ModuleId>> dependenciesByModule = new LinkedHashMap<>();
|
||||||
for (final var parsedSource : parsedSourceFiles) {
|
for (final var parsedSource : parsedSourceFiles) {
|
||||||
final var moduleDependencies = dependenciesByModule.computeIfAbsent(
|
final var moduleDependencies = dependenciesByModule.computeIfAbsent(
|
||||||
parsedSource.moduleId(),
|
parsedSource.moduleId(),
|
||||||
ignored -> new HashSet<>());
|
ignored -> new LinkedHashSet<>());
|
||||||
for (final var importDecl : parsedSource.ast().imports()) {
|
for (final var importDecl : parsedSource.ast().imports()) {
|
||||||
final var moduleRef = importDecl.moduleRef();
|
final var moduleRef = importDecl.moduleRef();
|
||||||
moduleDependencies.add(moduleId(moduleTable, moduleRef.project(), moduleRef.pathSegments()));
|
moduleDependencies.add(moduleId(moduleTable, moduleRef.project(), moduleRef.pathSegments()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return dependenciesByModule;
|
final Map<ModuleId, ReadOnlyList<ModuleId>> ordered = new LinkedHashMap<>();
|
||||||
|
for (final var entry : dependenciesByModule.entrySet()) {
|
||||||
|
ordered.put(entry.getKey(), ReadOnlyList.wrap(new ArrayList<>(entry.getValue())));
|
||||||
|
}
|
||||||
|
return java.util.Collections.unmodifiableMap(ordered);
|
||||||
}
|
}
|
||||||
|
|
||||||
private ModuleId moduleId(
|
private ModuleId moduleId(
|
||||||
|
|||||||
+75
@@ -1,61 +1,136 @@
|
|||||||
|
[Doc(markdown = """
|
||||||
|
Represents a packed RGBA color.
|
||||||
|
""")]
|
||||||
[BuiltinType(name = "color", version = 1)]
|
[BuiltinType(name = "color", version = 1)]
|
||||||
declare builtin type Color(
|
declare builtin type Color(
|
||||||
pub raw: int
|
pub raw: int
|
||||||
) {
|
) {
|
||||||
|
[Doc(markdown = """
|
||||||
|
Builds a color from its packed integer representation.
|
||||||
|
|
||||||
|
- `raw`: packed color value.
|
||||||
|
""")]
|
||||||
[IntrinsicCall(name = "from_raw", version = 1)]
|
[IntrinsicCall(name = "from_raw", version = 1)]
|
||||||
fn from_raw(raw: int) -> Color;
|
fn from_raw(raw: int) -> Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Builds an opaque color from red, green, and blue channels.
|
||||||
|
|
||||||
|
- `r`: red channel.
|
||||||
|
- `g`: green channel.
|
||||||
|
- `b`: blue channel.
|
||||||
|
""")]
|
||||||
[IntrinsicCall(name = "rgb", version = 1)]
|
[IntrinsicCall(name = "rgb", version = 1)]
|
||||||
fn rgb(r: int, g: int, b: int) -> Color;
|
fn rgb(r: int, g: int, b: int) -> Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Builds a color from red, green, blue, and alpha channels.
|
||||||
|
|
||||||
|
- `r`: red channel.
|
||||||
|
- `g`: green channel.
|
||||||
|
- `b`: blue channel.
|
||||||
|
- `a`: alpha channel.
|
||||||
|
""")]
|
||||||
[IntrinsicCall(name = "rgba", version = 1)]
|
[IntrinsicCall(name = "rgba", version = 1)]
|
||||||
fn rgba(r: int, g: int, b: int, a: int) -> Color;
|
fn rgba(r: int, g: int, b: int, a: int) -> Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Parses a CSS-style RGBA color string.
|
||||||
|
|
||||||
|
- `value`: color text in HTML/CSS format.
|
||||||
|
""")]
|
||||||
[IntrinsicCall(name = "html_rgba", version = 1)]
|
[IntrinsicCall(name = "html_rgba", version = 1)]
|
||||||
fn html_rgba(value: str) -> Color;
|
fn html_rgba(value: str) -> Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Builds an opaque grayscale color.
|
||||||
|
|
||||||
|
- `value`: grayscale channel value.
|
||||||
|
""")]
|
||||||
[IntrinsicCall(name = "gray_scale", version = 1)]
|
[IntrinsicCall(name = "gray_scale", version = 1)]
|
||||||
fn gray_scale(value: int) -> Color;
|
fn gray_scale(value: int) -> Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Returns the packed RGB portion of this color.
|
||||||
|
""")]
|
||||||
[IntrinsicCall(name = "hex", version = 1)]
|
[IntrinsicCall(name = "hex", version = 1)]
|
||||||
fn hex() -> int;
|
fn hex() -> int;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Returns the alpha channel of this color.
|
||||||
|
""")]
|
||||||
[IntrinsicCall(name = "alpha", version = 1)]
|
[IntrinsicCall(name = "alpha", version = 1)]
|
||||||
fn alpha() -> int;
|
fn alpha() -> int;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque black.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "black", version = 1)]
|
[BuiltinConst(target = "color", name = "black", version = 1)]
|
||||||
declare const BLACK: Color;
|
declare const BLACK: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque white.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "white", version = 1)]
|
[BuiltinConst(target = "color", name = "white", version = 1)]
|
||||||
declare const WHITE: Color;
|
declare const WHITE: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque red.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "red", version = 1)]
|
[BuiltinConst(target = "color", name = "red", version = 1)]
|
||||||
declare const RED: Color;
|
declare const RED: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque green.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "green", version = 1)]
|
[BuiltinConst(target = "color", name = "green", version = 1)]
|
||||||
declare const GREEN: Color;
|
declare const GREEN: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque blue.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "blue", version = 1)]
|
[BuiltinConst(target = "color", name = "blue", version = 1)]
|
||||||
declare const BLUE: Color;
|
declare const BLUE: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque yellow.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "yellow", version = 1)]
|
[BuiltinConst(target = "color", name = "yellow", version = 1)]
|
||||||
declare const YELLOW: Color;
|
declare const YELLOW: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque orange.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "orange", version = 1)]
|
[BuiltinConst(target = "color", name = "orange", version = 1)]
|
||||||
declare const ORANGE: Color;
|
declare const ORANGE: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque indigo.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "indigo", version = 1)]
|
[BuiltinConst(target = "color", name = "indigo", version = 1)]
|
||||||
declare const INDIGO: Color;
|
declare const INDIGO: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque gray.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "gray", version = 1)]
|
[BuiltinConst(target = "color", name = "gray", version = 1)]
|
||||||
declare const GRAY: Color;
|
declare const GRAY: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque cyan.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "cyan", version = 1)]
|
[BuiltinConst(target = "color", name = "cyan", version = 1)]
|
||||||
declare const CYAN: Color;
|
declare const CYAN: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Opaque magenta.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "magenta", version = 1)]
|
[BuiltinConst(target = "color", name = "magenta", version = 1)]
|
||||||
declare const MAGENTA: Color;
|
declare const MAGENTA: Color;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Fully transparent color.
|
||||||
|
""")]
|
||||||
[BuiltinConst(target = "color", name = "transparent", version = 1)]
|
[BuiltinConst(target = "color", name = "transparent", version = 1)]
|
||||||
declare const TRANSPARENT: Color;
|
declare const TRANSPARENT: Color;
|
||||||
|
|||||||
+48
@@ -1,35 +1,83 @@
|
|||||||
|
[Doc(markdown = """
|
||||||
|
Low-level asset loading host bindings.
|
||||||
|
""")]
|
||||||
declare host LowAssets {
|
declare host LowAssets {
|
||||||
|
[Doc(markdown = """
|
||||||
|
Starts loading an addressable asset into a slot.
|
||||||
|
|
||||||
|
- `addressable`: asset reference.
|
||||||
|
- `slot`: destination slot.
|
||||||
|
""")]
|
||||||
[Host(module = "asset", name = "load", version = 1)]
|
[Host(module = "asset", name = "load", version = 1)]
|
||||||
[Capability(name = "asset")]
|
[Capability(name = "asset")]
|
||||||
[AssetLowering(param = 0)]
|
[AssetLowering(param = 0)]
|
||||||
fn load(addressable: Addressable, slot: int) -> (status: int, loading_handle: int);
|
fn load(addressable: Addressable, slot: int) -> (status: int, loading_handle: int);
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Reads the status of an asset loading operation.
|
||||||
|
|
||||||
|
- `loading_handle`: handle returned by `load`.
|
||||||
|
""")]
|
||||||
[Host(module = "asset", name = "status", version = 1)]
|
[Host(module = "asset", name = "status", version = 1)]
|
||||||
[Capability(name = "asset")]
|
[Capability(name = "asset")]
|
||||||
fn status(loading_handle: int) -> int;
|
fn status(loading_handle: int) -> int;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Commits a completed asset loading operation.
|
||||||
|
|
||||||
|
- `loading_handle`: handle returned by `load`.
|
||||||
|
""")]
|
||||||
[Host(module = "asset", name = "commit", version = 1)]
|
[Host(module = "asset", name = "commit", version = 1)]
|
||||||
[Capability(name = "asset")]
|
[Capability(name = "asset")]
|
||||||
fn commit(loading_handle: int) -> int;
|
fn commit(loading_handle: int) -> int;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Cancels an asset loading operation.
|
||||||
|
|
||||||
|
- `loading_handle`: handle returned by `load`.
|
||||||
|
""")]
|
||||||
[Host(module = "asset", name = "cancel", version = 1)]
|
[Host(module = "asset", name = "cancel", version = 1)]
|
||||||
[Capability(name = "asset")]
|
[Capability(name = "asset")]
|
||||||
fn cancel(loading_handle: int) -> int;
|
fn cancel(loading_handle: int) -> int;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
High-level asset loading commands.
|
||||||
|
""")]
|
||||||
declare service Assets {
|
declare service Assets {
|
||||||
|
[Doc(markdown = """
|
||||||
|
Starts loading an addressable asset into a slot.
|
||||||
|
|
||||||
|
- `addressable`: asset reference.
|
||||||
|
- `slot`: destination slot.
|
||||||
|
""")]
|
||||||
fn load(addressable: Addressable, slot: int) -> (status: int, loading_handle: int) {
|
fn load(addressable: Addressable, slot: int) -> (status: int, loading_handle: int) {
|
||||||
return LowAssets.load(addressable, slot);
|
return LowAssets.load(addressable, slot);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Reads the status of an asset loading operation.
|
||||||
|
|
||||||
|
- `loading_handle`: handle returned by `load`.
|
||||||
|
""")]
|
||||||
fn status(loading_handle: int) -> int {
|
fn status(loading_handle: int) -> int {
|
||||||
return LowAssets.status(loading_handle);
|
return LowAssets.status(loading_handle);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Commits a completed asset loading operation.
|
||||||
|
|
||||||
|
- `loading_handle`: handle returned by `load`.
|
||||||
|
""")]
|
||||||
fn commit(loading_handle: int) -> int {
|
fn commit(loading_handle: int) -> int {
|
||||||
return LowAssets.commit(loading_handle);
|
return LowAssets.commit(loading_handle);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Cancels an asset loading operation.
|
||||||
|
|
||||||
|
- `loading_handle`: handle returned by `load`.
|
||||||
|
""")]
|
||||||
fn cancel(loading_handle: int) -> int {
|
fn cancel(loading_handle: int) -> int {
|
||||||
return LowAssets.cancel(loading_handle);
|
return LowAssets.cancel(loading_handle);
|
||||||
}
|
}
|
||||||
|
|||||||
+60
@@ -1,16 +1,46 @@
|
|||||||
|
[Doc(markdown = """
|
||||||
|
Low-level scene composer host bindings.
|
||||||
|
""")]
|
||||||
declare host LowComposer {
|
declare host LowComposer {
|
||||||
|
[Doc(markdown = """
|
||||||
|
Sets the scene camera position.
|
||||||
|
|
||||||
|
- `x`: camera x coordinate.
|
||||||
|
- `y`: camera y coordinate.
|
||||||
|
""")]
|
||||||
[Host(module = "composer", name = "set_camera", version = 1)]
|
[Host(module = "composer", name = "set_camera", version = 1)]
|
||||||
[Capability(name = "composer")]
|
[Capability(name = "composer")]
|
||||||
fn set_camera(x: int, y: int) -> void;
|
fn set_camera(x: int, y: int) -> void;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Binds a scene bank for composer emission.
|
||||||
|
|
||||||
|
- `scene_bank_id`: scene bank identifier.
|
||||||
|
""")]
|
||||||
[Host(module = "composer", name = "bind_scene", version = 1)]
|
[Host(module = "composer", name = "bind_scene", version = 1)]
|
||||||
[Capability(name = "composer")]
|
[Capability(name = "composer")]
|
||||||
fn bind_scene(scene_bank_id: int) -> int;
|
fn bind_scene(scene_bank_id: int) -> int;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Unbinds the active scene bank.
|
||||||
|
""")]
|
||||||
[Host(module = "composer", name = "unbind_scene", version = 1)]
|
[Host(module = "composer", name = "unbind_scene", version = 1)]
|
||||||
[Capability(name = "composer")]
|
[Capability(name = "composer")]
|
||||||
fn unbind_scene() -> int;
|
fn unbind_scene() -> int;
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Emits a sprite command into the active scene.
|
||||||
|
|
||||||
|
- `glyph_id`: glyph identifier.
|
||||||
|
- `palette_id`: palette identifier.
|
||||||
|
- `x`: screen x coordinate.
|
||||||
|
- `y`: screen y coordinate.
|
||||||
|
- `layer`: render layer.
|
||||||
|
- `bank_id`: asset bank identifier.
|
||||||
|
- `flip_x`: mirror horizontally.
|
||||||
|
- `flip_y`: mirror vertically.
|
||||||
|
- `priority`: ordering priority.
|
||||||
|
""")]
|
||||||
[Host(module = "composer", name = "emit_sprite", version = 1)]
|
[Host(module = "composer", name = "emit_sprite", version = 1)]
|
||||||
[Capability(name = "composer")]
|
[Capability(name = "composer")]
|
||||||
fn emit_sprite(
|
fn emit_sprite(
|
||||||
@@ -26,23 +56,53 @@ declare host LowComposer {
|
|||||||
) -> int;
|
) -> int;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
High-level scene composition commands.
|
||||||
|
""")]
|
||||||
declare service Composer
|
declare service Composer
|
||||||
{
|
{
|
||||||
|
[Doc(markdown = """
|
||||||
|
Sets the scene camera position.
|
||||||
|
|
||||||
|
- `x`: camera x coordinate.
|
||||||
|
- `y`: camera y coordinate.
|
||||||
|
""")]
|
||||||
fn set_camera(x: int, y: int) -> void
|
fn set_camera(x: int, y: int) -> void
|
||||||
{
|
{
|
||||||
LowComposer.set_camera(x, y);
|
LowComposer.set_camera(x, y);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Binds a scene bank for composer emission.
|
||||||
|
|
||||||
|
- `scene_bank_id`: scene bank identifier.
|
||||||
|
""")]
|
||||||
fn bind_scene(scene_bank_id: int) -> int
|
fn bind_scene(scene_bank_id: int) -> int
|
||||||
{
|
{
|
||||||
return LowComposer.bind_scene(scene_bank_id);
|
return LowComposer.bind_scene(scene_bank_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Unbinds the active scene bank.
|
||||||
|
""")]
|
||||||
fn unbind_scene() -> int
|
fn unbind_scene() -> int
|
||||||
{
|
{
|
||||||
return LowComposer.unbind_scene();
|
return LowComposer.unbind_scene();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Doc(markdown = """
|
||||||
|
Emits a sprite command into the active scene.
|
||||||
|
|
||||||
|
- `glyph_id`: glyph identifier.
|
||||||
|
- `palette_id`: palette identifier.
|
||||||
|
- `x`: screen x coordinate.
|
||||||
|
- `y`: screen y coordinate.
|
||||||
|
- `layer`: render layer.
|
||||||
|
- `bank_id`: asset bank identifier.
|
||||||
|
- `flip_x`: mirror horizontally.
|
||||||
|
- `flip_y`: mirror vertically.
|
||||||
|
- `priority`: ordering priority.
|
||||||
|
""")]
|
||||||
fn emit_sprite(
|
fn emit_sprite(
|
||||||
glyph_id: int,
|
glyph_id: int,
|
||||||
palette_id: int,
|
palette_id: int,
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user