From da8003f6d4a20849c0c34ba423509e5e2f71daf8 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sat, 5 Dec 2026 14:06:50 +0300 Subject: [PATCH] Implement the VLS roadmap on the native VBS build Native VBS and CMake builds of the server and every registered suite: protocol and document sync, VBS/compdb providers, stock GCC diagnostics (including in-process default profile preparation), the stock occurrence observer and hover/definition, the bounded Scheduler, C++ module graph, scan and artifact cache with real CMI production, the context-aware symbol index with schema-2 snapshot migration, navigation and guarded rename, reflection provenance with splice-origin extraction, index-backed completion and signature help, live GCC worker control with a registered DAP suite, and the Neovim and VS Code clients. VoidLibrary follows main. The private GCC 16.2.0 frontend is reproduced from the versioned patches and verified stepping reflection/template code with projected values 17/34 and 41/82. --- .gitignore | 7 + AGENTS.md | 22 +- CMakeLists.txt | 23 +- README.md | 182 +- build.cpp | 203 +++ build.profiles.cpp | 12 + clients/neovim/README.md | 55 + clients/neovim/lua/vls/init.lua | 367 ++++ clients/neovim/plugin/vls.lua | 92 + clients/vscode/README.md | 51 + clients/vscode/package-lock.json | 162 ++ clients/vscode/package.json | 130 ++ clients/vscode/src/extension.ts | 269 +++ clients/vscode/src/test/run.ts | 185 ++ clients/vscode/tsconfig.json | 19 + cmake/VoidDependency.cmake | 33 +- .../gcc-16.2.0/0001-evaluator-events.patch | 581 +++++++ .../gcc-16.2.0/0002-ide-occurrences.patch | 521 ++++++ .../0003-physical-utf8-origin.patch | 98 ++ .../gcc-16.2.0/0004-splice-origins.patch | 103 ++ compiler-patches/gcc-16.2.0/configure.args | 3 + docs/DEPENDENCIES.md | 39 +- docs/agent-workflow/APPROVED_PLAN.md | 8 + docs/agent-workflow/DECISIONS.md | 30 +- docs/agent-workflow/PREFLIGHT.md | 80 + docs/agent-workflow/RESUMPTION-2026-11-27.md | 90 + docs/agent-workflow/REVIEW.md | 70 + docs/agent-workflow/STATE.md | 237 ++- docs/agent-workflow/TASKS.md | 74 +- docs/agent-workflow/VERIFICATION.md | 956 ++++++++++- .../tasks/T-CLIENT-NEOVIM-023.md | 126 ++ .../tasks/T-CLIENT-VSCODE-022.md | 119 ++ .../tasks/T-CORPUS-MODULES-011.md | 48 + .../tasks/T-DAP-TRANSCRIPTS-020.md | 48 + .../tasks/T-DIAGNOSTIC-SARIF-013.md | 50 + docs/agent-workflow/tasks/T-DOCS-003.md | 75 + docs/agent-workflow/tasks/T-DOCS-PERF-006.md | 48 + .../tasks/T-FIX-DIAGNOSTIC-COLUMNS-013.md | 49 + .../tasks/T-GCC-EVALUATOR-017.md | 48 + docs/agent-workflow/tasks/T-GCC-IDE-008.md | 48 + docs/agent-workflow/tasks/T-GCC-LEAF-009.md | 48 + docs/agent-workflow/tasks/T-GCC-PREP-008.md | 49 + .../tasks/T-GCC-SUPERVISOR-018.md | 48 + docs/agent-workflow/tasks/T-GCC-TRACE-019.md | 48 + docs/agent-workflow/tasks/T-MODEL-005.md | 51 + .../tasks/T-MODULE-CORPUS-011.md | 48 + .../tasks/T-MODULE-GRAPH-011.md | 51 + docs/agent-workflow/tasks/T-NATIVE-001.md | 74 + docs/agent-workflow/tasks/T-NATIVE-PREP.md | 51 + docs/agent-workflow/tasks/T-PLAN-002.md | 149 ++ docs/agent-workflow/tasks/T-PLAN-006.md | 48 + docs/agent-workflow/tasks/T-PLAN-DAP-020.md | 48 + .../tasks/T-PLAN-EDITORS-022.md | 48 + docs/agent-workflow/tasks/T-PLAN-GCC-008.md | 48 + .../tasks/T-PLAN-SEMANTICS-010.md | 49 + .../tasks/T-PLAN-STOCK-NAVIGATION-014.md | 48 + docs/agent-workflow/tasks/T-PREFLIGHT-004.md | 114 ++ docs/agent-workflow/tasks/T-PREFLIGHT-007.md | 48 + .../tasks/T-PREFLIGHT-CATALOG-009.md | 48 + .../tasks/T-PREFLIGHT-DAP-020.md | 49 + .../tasks/T-PREFLIGHT-DIAGNOSTIC-013.md | 48 + .../tasks/T-PREFLIGHT-GCC-008.md | 49 + .../tasks/T-PREFLIGHT-LEASE-009.md | 48 + .../tasks/T-PREFLIGHT-MODULE-011.md | 49 + .../tasks/T-PREFLIGHT-REPLAY-020.md | 48 + .../tasks/T-PREFLIGHT-SOURCE-009.md | 48 + .../tasks/T-PREFLIGHT-STOCK-NAVIGATION-014.md | 48 + docs/agent-workflow/tasks/T-PROTOCOL-005.md | 57 + .../agent-workflow/tasks/T-PROVIDER-IO-007.md | 49 + .../tasks/T-PROVIDER-ROWS-007.md | 49 + .../tasks/T-PROVIDER-SESSION-007.md | 49 + .../tasks/T-PROVIDER-VBS-006.md | 49 + .../tasks/T-REPAIR-PROVIDER-007.md | 49 + .../tasks/T-REPLAY-RECORDING-019.md | 50 + .../tasks/T-REREVIEW-PROVIDER-007.md | 48 + docs/agent-workflow/tasks/T-RESEARCH-008.md | 96 ++ docs/agent-workflow/tasks/T-REVIEW-003.md | 89 + docs/agent-workflow/tasks/T-REVIEW-005.md | 48 + docs/agent-workflow/tasks/T-REVIEW-DAP-020.md | 48 + docs/agent-workflow/tasks/T-REVIEW-GCC-019.md | 49 + .../tasks/T-REVIEW-PROVIDER-007.md | 48 + .../tasks/T-REVIEW-SEMANTIC-013.md | 51 + .../tasks/T-SEMANTIC-LEASE-009.md | 50 + docs/agent-workflow/tasks/T-SESSION-003.md | 51 + .../tasks/T-SESSION-PASSIVE-007.md | 49 + .../tasks/T-SOURCE-CATALOG-009.md | 50 + .../tasks/T-SOURCE-OVERLAYS-009.md | 50 + .../tasks/T-STOCK-OCCURRENCES-014.md | 50 + docs/agent-workflow/tasks/T-TRUST-004.md | 67 + docs/roadmap/01-bootstrap-dependencies.md | 4 +- docs/roadmap/02-lsp-protocol-lifecycle.md | 4 +- docs/roadmap/03-documents-positions.md | 2 +- .../04-workspace-configuration-trust.md | 2 +- docs/roadmap/05-build-contexts.md | 2 +- docs/roadmap/06-native-vbs-tooling.md | 2 +- docs/roadmap/07-compilation-database.md | 2 +- docs/roadmap/08-frontend-feasibility.md | 4 +- docs/roadmap/09-semantic-workers.md | 6 +- docs/roadmap/10-scheduling-resources.md | 2 +- docs/roadmap/11-cpp-modules.md | 5 +- docs/roadmap/12-reflection-provenance.md | 2 +- docs/roadmap/13-diagnostics-recovery.md | 6 +- docs/roadmap/14-completion-hover.md | 2 +- docs/roadmap/15-index-persistence.md | 2 +- docs/roadmap/16-navigation-rename.md | 2 +- .../17-compiler-debug-instrumentation.md | 7 +- docs/roadmap/18-live-debugging.md | 2 +- docs/roadmap/19-trace-replay.md | 2 +- docs/roadmap/20-dap-service.md | 7 +- docs/roadmap/21-inspection-api.md | 9 +- docs/roadmap/23-neovim-client.md | 5 +- docs/roadmap/26-vbs-self-build-adoption.md | 8 +- docs/roadmap/README.md | 20 +- docs/roadmap/REQUIREMENTS.md | 15 +- .../frontend/gcc-observer/Observer.cpp | 724 ++++++++ experiments/frontend/gcc-worker/Leaf.cpp | 275 +++ experiments/frontend/gcc-worker/Leaf.hpp | 13 + experiments/frontend/gcc-worker/Main.cpp | 67 + .../frontend/gcc-worker/Supervisor.cpp | 374 +++++ .../frontend/gcc-worker/Supervisor.hpp | 18 + experiments/frontend/gcc-worker/Trace.cpp | 1300 ++++++++++++++ experiments/frontend/gcc-worker/Trace.hpp | 112 ++ include/Void/LanguageServer/Build/Model.hpp | 331 ++++ .../Void/LanguageServer/Build/Providers.hpp | 112 ++ .../Documents/DocumentSnapshot.hpp | 63 + .../Documents/DocumentStore.hpp | 215 +++ .../LanguageServer/Documents/Position.hpp | 75 + include/Void/LanguageServer/Documents/Uri.hpp | 41 + .../Void/LanguageServer/Protocol/Framing.hpp | 35 + include/Void/LanguageServer/Protocol/Json.hpp | 38 + .../LanguageServer/Support/RegularFile.hpp | 135 ++ .../Workspace/Configuration.hpp | 159 ++ .../Void/LanguageServer/Workspace/Trust.hpp | 165 ++ include/vls/DocumentSync.hpp | 18 + include/vls/Framing.hpp | 22 +- include/vls/Json.hpp | 41 +- include/vls/Server.hpp | 14 +- include/vls/WorkspaceSession.hpp | 90 + .../vls/debug/inspection/ReplaySession.hpp | 66 + include/vls/debug/live/LiveSession.hpp | 66 + include/vls/features/Completion.hpp | 95 ++ include/vls/features/IndexNavigation.hpp | 34 + include/vls/features/SignatureHelp.hpp | 62 + include/vls/index/SymbolIndex.hpp | 158 ++ include/vls/modules/ArtifactCache.hpp | 83 + include/vls/modules/GccArtifacts.hpp | 39 + include/vls/modules/GccScan.hpp | 45 + include/vls/modules/ModuleGraph.hpp | 227 +++ include/vls/modules/ModuleWorkQueue.hpp | 57 + include/vls/modules/ScanCommand.hpp | 34 + include/vls/modules/ScheduledArtifacts.hpp | 23 + include/vls/navigation/Navigation.hpp | 111 ++ include/vls/reflection/Provenance.hpp | 243 +++ include/vls/scheduler/Scheduler.hpp | 82 + include/vls/semantic/Diagnostics.hpp | 109 ++ include/vls/semantic/EditorDiagnostics.hpp | 65 + include/vls/semantic/Occurrences.hpp | 42 + include/vls/semantic/SourceCatalog.hpp | 118 ++ include/vls/semantic/StockCompiler.hpp | 79 + src/Build/CommandImport.cpp | 692 ++++++++ src/Build/CompdbProvider.cpp | 51 + src/Build/Model.cpp | 600 +++++++ src/Build/ProviderFile.cpp | 522 ++++++ src/Build/VbsProvider.cpp | 272 +++ src/DocumentSync.cpp | 136 ++ src/Documents/DocumentSnapshot.cpp | 38 + src/Documents/DocumentStore.cpp | 659 ++++++++ src/Documents/Position.cpp | 299 ++++ src/Documents/Uri.cpp | 237 +++ src/Json.cpp | 99 -- src/{ => Protocol}/Framing.cpp | 112 +- src/Protocol/Json.cpp | 160 ++ src/Server.cpp | 375 ++++- src/Workspace/Configuration.cpp | 467 +++++ src/Workspace/Trust.cpp | 615 +++++++ src/WorkspaceSession.cpp | 1495 +++++++++++++++++ src/debug/Fields.hpp | 26 + src/debug/dap/Main.cpp | 681 ++++++++ src/debug/dap/Projection.cpp | 163 ++ src/debug/dap/Projection.hpp | 17 + src/debug/inspection/ReplaySession.cpp | 215 +++ src/debug/live/LiveSession.cpp | 327 ++++ src/features/Completion.cpp | 135 ++ src/features/IndexNavigation.cpp | 74 + src/features/SignatureHelp.cpp | 258 +++ src/index/SymbolIndex.cpp | 709 ++++++++ src/main.cpp | 144 +- src/modules/ArtifactCache.cpp | 328 ++++ src/modules/GccArtifacts.cpp | 119 ++ src/modules/GccScan.cpp | 121 ++ src/modules/ModuleGraph.cpp | 672 ++++++++ src/modules/ModuleWorkQueue.cpp | 86 + src/modules/ScanCommand.cpp | 65 + src/modules/ScheduledArtifacts.cpp | 119 ++ src/navigation/Navigation.cpp | 132 ++ src/reflection/Provenance.cpp | 541 ++++++ src/scheduler/Scheduler.cpp | 315 ++++ src/semantic/Diagnostics.cpp | 399 +++++ src/semantic/EditorDiagnostics.cpp | 1193 +++++++++++++ src/semantic/Occurrences.cpp | 195 +++ src/semantic/SourceCatalog.cpp | 483 ++++++ src/semantic/StockCompiler.cpp | 1075 ++++++++++++ tests/CMakeLists.txt | 87 +- tests/FramingTests.cpp | 14 +- tests/JsonCapabilities.cpp | 53 +- tests/JsonTests.cpp | 12 +- tests/LifecycleTests.cpp | 21 +- tests/NativeRegistration.cpp | 74 + tests/ProcessTests.cpp | 107 +- tests/ProtocolEncodingTests.cpp | 184 ++ tests/ProviderProcessTests.cpp | 228 +++ tests/Registration.cmake | 32 - tests/TestExecutable.hpp | 17 + tests/TestSupport.hpp | 18 +- tests/corpus/frontend/README.md | 63 + tests/corpus/frontend/enum.cpp | 25 + tests/corpus/frontend/expansion-static.cpp | 17 + tests/corpus/frontend/gate.cppm | 9 + tests/corpus/frontend/gcc-evaluation.cpp | 16 + tests/corpus/frontend/gcc-live.cpp | 20 + tests/corpus/frontend/gcc-queries.cpp | 12 + tests/corpus/frontend/importer.cpp | 8 + tests/corpus/frontend/invalid-name.cpp | 8 + tests/corpus/frontend/invalid-splice.cpp | 8 + tests/corpus/frontend/library.cpp | 11 + tests/corpus/frontend/probe-clang.py | 78 + tests/corpus/frontend/probe-gcc-tooling.py | 156 ++ tests/corpus/frontend/range-static.cpp | 10 + tests/corpus/frontend/range.cpp | 10 + tests/corpus/frontend/verify-gcc-events.py | 550 ++++++ tests/corpus/frontend/verify-gcc-ide.py | 292 ++++ tests/corpus/frontend/verify-gcc.py | 72 + .../frontend/verify-stock-diagnostics.py | 300 ++++ tests/corpus/frontend/verify-stock-gcc-gdb.py | 140 ++ .../corpus/frontend/verify-stock-observer.py | 399 +++++ tests/corpus/modules/api.cppm | 20 + tests/corpus/modules/config/seed.hpp | 3 + tests/corpus/modules/config/value.hpp | 3 + tests/corpus/modules/cycle-a.cppm | 2 + tests/corpus/modules/cycle-b.cppm | 2 + tests/corpus/modules/detail.cppm | 7 + tests/corpus/modules/header-importer.cpp | 13 + tests/corpus/modules/implementation.cpp | 8 + tests/corpus/modules/importer.cpp | 8 + tests/corpus/modules/include/vls-unit.hpp | 3 + tests/corpus/modules/missing-provider.cpp | 1 + tests/corpus/modules/private-fragment.cppm | 7 + tests/corpus/modules/shadow/vls-unit.hpp | 1 + tests/corpus/modules/std-importer.cpp | 1 + tests/corpus/modules/system-importer.cpp | 3 + tests/corpus/modules/topology.cppm | 6 + tests/corpus/modules/verify.py | 580 +++++++ tests/corpus/modules/visibility.cpp | 6 + tests/debug/DapReplayTests.cpp | 354 ++++ tests/debug/LiveDapTests.cpp | 199 +++ tests/debug/LiveSessionTests.cpp | 112 ++ tests/debug/LiveWorkerFixture.cpp | 79 + tests/debug/RecordingTests.cpp | 506 ++++++ tests/debug/TraceTests.cpp | 575 +++++++ tests/debug/fixtures/cancelled-41.vls | Bin 0 -> 2620 bytes tests/debug/fixtures/integral-17.vls | Bin 0 -> 6166 bytes tests/debug/fixtures/integral-41.vls | Bin 0 -> 6166 bytes tests/documents/BoundInputTests.cpp | 452 +++++ tests/documents/DocumentTests.cpp | 629 +++++++ tests/documents/LongLineTests.cpp | 139 ++ tests/features/CompletionTests.cpp | 143 ++ tests/features/IndexNavigationTests.cpp | 157 ++ tests/features/SignatureHelpTests.cpp | 159 ++ tests/index/SymbolIndexTests.cpp | 443 +++++ tests/modules/ArtifactCacheTests.cpp | 307 ++++ tests/modules/GccScanFixture.cpp | 247 +++ tests/modules/ModuleArtifactFixture.cpp | 288 ++++ tests/modules/ModuleGraphTests.cpp | 593 +++++++ tests/modules/ModuleWorkQueueTests.cpp | 198 +++ tests/modules/ScanCommandTests.cpp | 52 + tests/native/DapReplay.py | 319 ++++ tests/native/EditorModules.py | 167 ++ tests/native/GccLeaf.py | 156 ++ tests/native/GccSupervisor.py | 217 +++ tests/native/InstalledServer.py | 122 ++ tests/native/LiveDap.py | 151 ++ tests/native/NeovimClient.lua | 109 ++ tests/native/NeovimDiagnostics.lua | 56 + tests/native/NeovimRename.lua | 85 + tests/native/NeovimReplay.lua | 68 + tests/native/Preparation.py | 273 +++ tests/native/StockDiagnostics.py | 238 +++ tests/native/StockOccurrences.py | 274 +++ tests/native/VscodeClient.py | 80 + tests/navigation/NavigationTests.cpp | 183 ++ tests/performance/document_sync.py | 117 ++ tests/providers/CommandImportTests.cpp | 605 +++++++ tests/providers/CompdbProviderTests.cpp | 39 + tests/providers/ModelTests.cpp | 642 +++++++ tests/providers/ProviderFileTests.cpp | 202 +++ tests/providers/ProviderFixture.hpp | 93 + tests/providers/VbsProviderTests.cpp | 185 ++ tests/reflection/ProvenanceTests.cpp | 496 ++++++ tests/scheduler/SchedulerTests.cpp | 295 ++++ tests/semantic/DiagnosticTests.cpp | 335 ++++ tests/semantic/GccDiagnosticFixture.cpp | 260 +++ tests/semantic/OccurrenceTests.cpp | 188 +++ tests/semantic/SourceCatalogTests.cpp | 362 ++++ tests/workspace/ProviderSessionTests.cpp | 556 ++++++ tests/workspace/SemanticLeaseTests.cpp | 589 +++++++ tests/workspace/WorkspaceTests.cpp | 611 +++++++ tools/prepare-gcc-observer | 201 +++ tools/prepare-gcc-profile | 133 ++ tools/prepare-private-gcc | 115 ++ tools/prepare-voidlibrary | 273 +++ 310 files changed, 47552 insertions(+), 480 deletions(-) create mode 100644 build.cpp create mode 100644 build.profiles.cpp create mode 100644 clients/neovim/README.md create mode 100644 clients/neovim/lua/vls/init.lua create mode 100644 clients/neovim/plugin/vls.lua create mode 100644 clients/vscode/README.md create mode 100644 clients/vscode/package-lock.json create mode 100644 clients/vscode/package.json create mode 100644 clients/vscode/src/extension.ts create mode 100644 clients/vscode/src/test/run.ts create mode 100644 clients/vscode/tsconfig.json create mode 100644 compiler-patches/gcc-16.2.0/0001-evaluator-events.patch create mode 100644 compiler-patches/gcc-16.2.0/0002-ide-occurrences.patch create mode 100644 compiler-patches/gcc-16.2.0/0003-physical-utf8-origin.patch create mode 100644 compiler-patches/gcc-16.2.0/0004-splice-origins.patch create mode 100644 compiler-patches/gcc-16.2.0/configure.args create mode 100644 docs/agent-workflow/RESUMPTION-2026-11-27.md create mode 100644 docs/agent-workflow/tasks/T-CLIENT-NEOVIM-023.md create mode 100644 docs/agent-workflow/tasks/T-CLIENT-VSCODE-022.md create mode 100644 docs/agent-workflow/tasks/T-CORPUS-MODULES-011.md create mode 100644 docs/agent-workflow/tasks/T-DAP-TRANSCRIPTS-020.md create mode 100644 docs/agent-workflow/tasks/T-DIAGNOSTIC-SARIF-013.md create mode 100644 docs/agent-workflow/tasks/T-DOCS-003.md create mode 100644 docs/agent-workflow/tasks/T-DOCS-PERF-006.md create mode 100644 docs/agent-workflow/tasks/T-FIX-DIAGNOSTIC-COLUMNS-013.md create mode 100644 docs/agent-workflow/tasks/T-GCC-EVALUATOR-017.md create mode 100644 docs/agent-workflow/tasks/T-GCC-IDE-008.md create mode 100644 docs/agent-workflow/tasks/T-GCC-LEAF-009.md create mode 100644 docs/agent-workflow/tasks/T-GCC-PREP-008.md create mode 100644 docs/agent-workflow/tasks/T-GCC-SUPERVISOR-018.md create mode 100644 docs/agent-workflow/tasks/T-GCC-TRACE-019.md create mode 100644 docs/agent-workflow/tasks/T-MODEL-005.md create mode 100644 docs/agent-workflow/tasks/T-MODULE-CORPUS-011.md create mode 100644 docs/agent-workflow/tasks/T-MODULE-GRAPH-011.md create mode 100644 docs/agent-workflow/tasks/T-NATIVE-001.md create mode 100644 docs/agent-workflow/tasks/T-NATIVE-PREP.md create mode 100644 docs/agent-workflow/tasks/T-PLAN-002.md create mode 100644 docs/agent-workflow/tasks/T-PLAN-006.md create mode 100644 docs/agent-workflow/tasks/T-PLAN-DAP-020.md create mode 100644 docs/agent-workflow/tasks/T-PLAN-EDITORS-022.md create mode 100644 docs/agent-workflow/tasks/T-PLAN-GCC-008.md create mode 100644 docs/agent-workflow/tasks/T-PLAN-SEMANTICS-010.md create mode 100644 docs/agent-workflow/tasks/T-PLAN-STOCK-NAVIGATION-014.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-004.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-007.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-CATALOG-009.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-DAP-020.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-DIAGNOSTIC-013.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-GCC-008.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-LEASE-009.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-MODULE-011.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-REPLAY-020.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-SOURCE-009.md create mode 100644 docs/agent-workflow/tasks/T-PREFLIGHT-STOCK-NAVIGATION-014.md create mode 100644 docs/agent-workflow/tasks/T-PROTOCOL-005.md create mode 100644 docs/agent-workflow/tasks/T-PROVIDER-IO-007.md create mode 100644 docs/agent-workflow/tasks/T-PROVIDER-ROWS-007.md create mode 100644 docs/agent-workflow/tasks/T-PROVIDER-SESSION-007.md create mode 100644 docs/agent-workflow/tasks/T-PROVIDER-VBS-006.md create mode 100644 docs/agent-workflow/tasks/T-REPAIR-PROVIDER-007.md create mode 100644 docs/agent-workflow/tasks/T-REPLAY-RECORDING-019.md create mode 100644 docs/agent-workflow/tasks/T-REREVIEW-PROVIDER-007.md create mode 100644 docs/agent-workflow/tasks/T-RESEARCH-008.md create mode 100644 docs/agent-workflow/tasks/T-REVIEW-003.md create mode 100644 docs/agent-workflow/tasks/T-REVIEW-005.md create mode 100644 docs/agent-workflow/tasks/T-REVIEW-DAP-020.md create mode 100644 docs/agent-workflow/tasks/T-REVIEW-GCC-019.md create mode 100644 docs/agent-workflow/tasks/T-REVIEW-PROVIDER-007.md create mode 100644 docs/agent-workflow/tasks/T-REVIEW-SEMANTIC-013.md create mode 100644 docs/agent-workflow/tasks/T-SEMANTIC-LEASE-009.md create mode 100644 docs/agent-workflow/tasks/T-SESSION-003.md create mode 100644 docs/agent-workflow/tasks/T-SESSION-PASSIVE-007.md create mode 100644 docs/agent-workflow/tasks/T-SOURCE-CATALOG-009.md create mode 100644 docs/agent-workflow/tasks/T-SOURCE-OVERLAYS-009.md create mode 100644 docs/agent-workflow/tasks/T-STOCK-OCCURRENCES-014.md create mode 100644 docs/agent-workflow/tasks/T-TRUST-004.md create mode 100644 experiments/frontend/gcc-observer/Observer.cpp create mode 100644 experiments/frontend/gcc-worker/Leaf.cpp create mode 100644 experiments/frontend/gcc-worker/Leaf.hpp create mode 100644 experiments/frontend/gcc-worker/Main.cpp create mode 100644 experiments/frontend/gcc-worker/Supervisor.cpp create mode 100644 experiments/frontend/gcc-worker/Supervisor.hpp create mode 100644 experiments/frontend/gcc-worker/Trace.cpp create mode 100644 experiments/frontend/gcc-worker/Trace.hpp create mode 100644 include/Void/LanguageServer/Build/Model.hpp create mode 100644 include/Void/LanguageServer/Build/Providers.hpp create mode 100644 include/Void/LanguageServer/Documents/DocumentSnapshot.hpp create mode 100644 include/Void/LanguageServer/Documents/DocumentStore.hpp create mode 100644 include/Void/LanguageServer/Documents/Position.hpp create mode 100644 include/Void/LanguageServer/Documents/Uri.hpp create mode 100644 include/Void/LanguageServer/Protocol/Framing.hpp create mode 100644 include/Void/LanguageServer/Protocol/Json.hpp create mode 100644 include/Void/LanguageServer/Support/RegularFile.hpp create mode 100644 include/Void/LanguageServer/Workspace/Configuration.hpp create mode 100644 include/Void/LanguageServer/Workspace/Trust.hpp create mode 100644 include/vls/DocumentSync.hpp create mode 100644 include/vls/WorkspaceSession.hpp create mode 100644 include/vls/debug/inspection/ReplaySession.hpp create mode 100644 include/vls/debug/live/LiveSession.hpp create mode 100644 include/vls/features/Completion.hpp create mode 100644 include/vls/features/IndexNavigation.hpp create mode 100644 include/vls/features/SignatureHelp.hpp create mode 100644 include/vls/index/SymbolIndex.hpp create mode 100644 include/vls/modules/ArtifactCache.hpp create mode 100644 include/vls/modules/GccArtifacts.hpp create mode 100644 include/vls/modules/GccScan.hpp create mode 100644 include/vls/modules/ModuleGraph.hpp create mode 100644 include/vls/modules/ModuleWorkQueue.hpp create mode 100644 include/vls/modules/ScanCommand.hpp create mode 100644 include/vls/modules/ScheduledArtifacts.hpp create mode 100644 include/vls/navigation/Navigation.hpp create mode 100644 include/vls/reflection/Provenance.hpp create mode 100644 include/vls/scheduler/Scheduler.hpp create mode 100644 include/vls/semantic/Diagnostics.hpp create mode 100644 include/vls/semantic/EditorDiagnostics.hpp create mode 100644 include/vls/semantic/Occurrences.hpp create mode 100644 include/vls/semantic/SourceCatalog.hpp create mode 100644 include/vls/semantic/StockCompiler.hpp create mode 100644 src/Build/CommandImport.cpp create mode 100644 src/Build/CompdbProvider.cpp create mode 100644 src/Build/Model.cpp create mode 100644 src/Build/ProviderFile.cpp create mode 100644 src/Build/VbsProvider.cpp create mode 100644 src/DocumentSync.cpp create mode 100644 src/Documents/DocumentSnapshot.cpp create mode 100644 src/Documents/DocumentStore.cpp create mode 100644 src/Documents/Position.cpp create mode 100644 src/Documents/Uri.cpp delete mode 100644 src/Json.cpp rename src/{ => Protocol}/Framing.cpp (61%) create mode 100644 src/Protocol/Json.cpp create mode 100644 src/Workspace/Configuration.cpp create mode 100644 src/Workspace/Trust.cpp create mode 100644 src/WorkspaceSession.cpp create mode 100644 src/debug/Fields.hpp create mode 100644 src/debug/dap/Main.cpp create mode 100644 src/debug/dap/Projection.cpp create mode 100644 src/debug/dap/Projection.hpp create mode 100644 src/debug/inspection/ReplaySession.cpp create mode 100644 src/debug/live/LiveSession.cpp create mode 100644 src/features/Completion.cpp create mode 100644 src/features/IndexNavigation.cpp create mode 100644 src/features/SignatureHelp.cpp create mode 100644 src/index/SymbolIndex.cpp create mode 100644 src/modules/ArtifactCache.cpp create mode 100644 src/modules/GccArtifacts.cpp create mode 100644 src/modules/GccScan.cpp create mode 100644 src/modules/ModuleGraph.cpp create mode 100644 src/modules/ModuleWorkQueue.cpp create mode 100644 src/modules/ScanCommand.cpp create mode 100644 src/modules/ScheduledArtifacts.cpp create mode 100644 src/navigation/Navigation.cpp create mode 100644 src/reflection/Provenance.cpp create mode 100644 src/scheduler/Scheduler.cpp create mode 100644 src/semantic/Diagnostics.cpp create mode 100644 src/semantic/EditorDiagnostics.cpp create mode 100644 src/semantic/Occurrences.cpp create mode 100644 src/semantic/SourceCatalog.cpp create mode 100644 src/semantic/StockCompiler.cpp create mode 100644 tests/NativeRegistration.cpp create mode 100644 tests/ProtocolEncodingTests.cpp create mode 100644 tests/ProviderProcessTests.cpp delete mode 100644 tests/Registration.cmake create mode 100644 tests/TestExecutable.hpp create mode 100644 tests/corpus/frontend/README.md create mode 100644 tests/corpus/frontend/enum.cpp create mode 100644 tests/corpus/frontend/expansion-static.cpp create mode 100644 tests/corpus/frontend/gate.cppm create mode 100644 tests/corpus/frontend/gcc-evaluation.cpp create mode 100644 tests/corpus/frontend/gcc-live.cpp create mode 100644 tests/corpus/frontend/gcc-queries.cpp create mode 100644 tests/corpus/frontend/importer.cpp create mode 100644 tests/corpus/frontend/invalid-name.cpp create mode 100644 tests/corpus/frontend/invalid-splice.cpp create mode 100644 tests/corpus/frontend/library.cpp create mode 100644 tests/corpus/frontend/probe-clang.py create mode 100644 tests/corpus/frontend/probe-gcc-tooling.py create mode 100644 tests/corpus/frontend/range-static.cpp create mode 100644 tests/corpus/frontend/range.cpp create mode 100644 tests/corpus/frontend/verify-gcc-events.py create mode 100644 tests/corpus/frontend/verify-gcc-ide.py create mode 100644 tests/corpus/frontend/verify-gcc.py create mode 100644 tests/corpus/frontend/verify-stock-diagnostics.py create mode 100644 tests/corpus/frontend/verify-stock-gcc-gdb.py create mode 100755 tests/corpus/frontend/verify-stock-observer.py create mode 100644 tests/corpus/modules/api.cppm create mode 100644 tests/corpus/modules/config/seed.hpp create mode 100644 tests/corpus/modules/config/value.hpp create mode 100644 tests/corpus/modules/cycle-a.cppm create mode 100644 tests/corpus/modules/cycle-b.cppm create mode 100644 tests/corpus/modules/detail.cppm create mode 100644 tests/corpus/modules/header-importer.cpp create mode 100644 tests/corpus/modules/implementation.cpp create mode 100644 tests/corpus/modules/importer.cpp create mode 100644 tests/corpus/modules/include/vls-unit.hpp create mode 100644 tests/corpus/modules/missing-provider.cpp create mode 100644 tests/corpus/modules/private-fragment.cppm create mode 100644 tests/corpus/modules/shadow/vls-unit.hpp create mode 100644 tests/corpus/modules/std-importer.cpp create mode 100644 tests/corpus/modules/system-importer.cpp create mode 100644 tests/corpus/modules/topology.cppm create mode 100644 tests/corpus/modules/verify.py create mode 100644 tests/corpus/modules/visibility.cpp create mode 100644 tests/debug/DapReplayTests.cpp create mode 100644 tests/debug/LiveDapTests.cpp create mode 100644 tests/debug/LiveSessionTests.cpp create mode 100644 tests/debug/LiveWorkerFixture.cpp create mode 100644 tests/debug/RecordingTests.cpp create mode 100644 tests/debug/TraceTests.cpp create mode 100644 tests/debug/fixtures/cancelled-41.vls create mode 100644 tests/debug/fixtures/integral-17.vls create mode 100644 tests/debug/fixtures/integral-41.vls create mode 100644 tests/documents/BoundInputTests.cpp create mode 100644 tests/documents/DocumentTests.cpp create mode 100644 tests/documents/LongLineTests.cpp create mode 100644 tests/features/CompletionTests.cpp create mode 100644 tests/features/IndexNavigationTests.cpp create mode 100644 tests/features/SignatureHelpTests.cpp create mode 100644 tests/index/SymbolIndexTests.cpp create mode 100644 tests/modules/ArtifactCacheTests.cpp create mode 100644 tests/modules/GccScanFixture.cpp create mode 100644 tests/modules/ModuleArtifactFixture.cpp create mode 100644 tests/modules/ModuleGraphTests.cpp create mode 100644 tests/modules/ModuleWorkQueueTests.cpp create mode 100644 tests/modules/ScanCommandTests.cpp create mode 100644 tests/native/DapReplay.py create mode 100644 tests/native/EditorModules.py create mode 100644 tests/native/GccLeaf.py create mode 100644 tests/native/GccSupervisor.py create mode 100644 tests/native/InstalledServer.py create mode 100644 tests/native/LiveDap.py create mode 100644 tests/native/NeovimClient.lua create mode 100644 tests/native/NeovimDiagnostics.lua create mode 100644 tests/native/NeovimRename.lua create mode 100644 tests/native/NeovimReplay.lua create mode 100644 tests/native/Preparation.py create mode 100644 tests/native/StockDiagnostics.py create mode 100644 tests/native/StockOccurrences.py create mode 100644 tests/native/VscodeClient.py create mode 100644 tests/navigation/NavigationTests.cpp create mode 100644 tests/performance/document_sync.py create mode 100644 tests/providers/CommandImportTests.cpp create mode 100644 tests/providers/CompdbProviderTests.cpp create mode 100644 tests/providers/ModelTests.cpp create mode 100644 tests/providers/ProviderFileTests.cpp create mode 100644 tests/providers/ProviderFixture.hpp create mode 100644 tests/providers/VbsProviderTests.cpp create mode 100644 tests/reflection/ProvenanceTests.cpp create mode 100644 tests/scheduler/SchedulerTests.cpp create mode 100644 tests/semantic/DiagnosticTests.cpp create mode 100644 tests/semantic/GccDiagnosticFixture.cpp create mode 100644 tests/semantic/OccurrenceTests.cpp create mode 100644 tests/semantic/SourceCatalogTests.cpp create mode 100644 tests/workspace/ProviderSessionTests.cpp create mode 100644 tests/workspace/SemanticLeaseTests.cpp create mode 100644 tests/workspace/WorkspaceTests.cpp create mode 100755 tools/prepare-gcc-observer create mode 100755 tools/prepare-gcc-profile create mode 100755 tools/prepare-private-gcc create mode 100755 tools/prepare-voidlibrary diff --git a/.gitignore b/.gitignore index a701200..0119e30 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ # Build and local runtime state /build/ /build-*/ +/.vbs/ +/vbs.lock /.vls/ /.serena/ /.cache/ @@ -19,3 +21,8 @@ CMakeUserPresets.json *.swp *~ .DS_Store +# VS Code client build outputs and fetched dependencies +/clients/vscode/node_modules/ +/clients/vscode/out/ +__pycache__/ +*.pyc diff --git a/AGENTS.md b/AGENTS.md index c8ab27e..cb4c4c0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,27 +1,35 @@ # VoidLanguageServer development Read docs/agent-workflow/STATE.md and TASKS.md, then the relevant roadmap. -The approved current scope is repository initialization, detailed plans and a -compiling LSP lifecycle shell. Compiler semantics, native VBS integration, indexing, -debugging and editor plugins remain future milestones until implemented and verified. +The user authorized implementation of the full roadmap on2026-11-27. Preserve all +requirements, dependency gates and acceptance criteria. Compiler semantics, native +VBS integration, indexing, debugging and editor plugins remain incomplete until +implemented and verified. The executable supports incremental document sync, +passive build context selection and opt-in stock GCC diagnostics. ## Build and dependency rules +VoidBuildSystem is the primary build system per D-025. From the repository root +run `tools/prepare-voidlibrary`, then `vbs build` and `vbs test` with the same +absolute build directory and profile. See README.md for the full commands and +the tested VBS install prerequisite. CMake remains available for comparison. Use `dev cpp-gcc -c COMMAND...` (observed GCC 16.2.0). The bootstrap uses C++26, -freflection, CMake 4+ and Ninja. Per user decision D-021, VoidLibrary follows main; do not restore a commit pin without a new user instruction. Record the exact tested commit in docs/agent-workflow/VERIFICATION.md. The explicit VLS_VOID_SOURCE_DIR override is development-only; never modify the external checkout or copy its secrets. -VoidLibrary's decimal support is an upstream prerequisite. Do not implement a -competing decimal parser or claim JSON conformance before the capability suite passes. +VoidLibrary main now includes decimal support; record the actual tested revision +and require the JSON capability suite to pass. Do not implement a competing parser. -Planned bootstrap checks, once CMakeLists.txt exists: +Comparison checks ```sh dev cpp-gcc -c cmake -S . -B build/bootstrap -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON dev cpp-gcc -c cmake --build build/bootstrap dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure ``` Use the actual registered tests; zero tests is not success. Format only owned C++ paths. +To refresh the fetched dependency, add --fresh to configuration and restate required +cache settings. Ordinary CMake4 reconfiguration can reuse dependency population stamps. ## Contracts - stdout is protocol-only in stdio mode; diagnostics use stderr. @@ -39,6 +47,6 @@ Use the supplied Astra/Sol workflow and precise linted task specs. Workers share checkout unless isolation is established. Root owns docs, decisions, Git initialization and integration. Read TASKS.md for active source ownership before editing. No staging, commits, remote setup, pushing, deployment or sibling-repository changes -are authorized by the bootstrap task. Never reset, stash, clean or overwrite unrelated work. +are authorized by the implementation goal. Never reset, stash, clean or overwrite unrelated work. Do not inspect/index .env files, keys, WG.conf, credentials or ignored caches. No global Nix configuration changes, generated CODEX_HOME edits or tool installers. diff --git a/CMakeLists.txt b/CMakeLists.txt index 58f9dd9..ae0ba2f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -24,9 +24,15 @@ set(VLS_VOID_REF "main") include(cmake/VoidDependency.cmake) vls_add_void_dependency() -add_library(vls_protocol STATIC src/Framing.cpp src/Json.cpp src/Server.cpp) +add_library(vls_protocol STATIC src/Protocol/Framing.cpp src/Protocol/Json.cpp + src/Documents/DocumentSnapshot.cpp src/Documents/DocumentStore.cpp src/Documents/Position.cpp + src/Documents/Uri.cpp src/Workspace/Configuration.cpp src/Workspace/Trust.cpp src/Build/Model.cpp + src/Build/ProviderFile.cpp src/Build/CommandImport.cpp src/Build/VbsProvider.cpp + src/Build/CompdbProvider.cpp src/DocumentSync.cpp src/WorkspaceSession.cpp src/Server.cpp + src/semantic/Diagnostics.cpp src/semantic/SourceCatalog.cpp src/semantic/StockCompiler.cpp src/semantic/EditorDiagnostics.cpp src/semantic/Occurrences.cpp src/scheduler/Scheduler.cpp + src/modules/ModuleGraph.cpp src/modules/ArtifactCache.cpp src/modules/GccArtifacts.cpp src/modules/ScheduledArtifacts.cpp src/index/SymbolIndex.cpp src/navigation/Navigation.cpp src/reflection/Provenance.cpp src/features/Completion.cpp src/features/IndexNavigation.cpp src/features/SignatureHelp.cpp src/debug/live/LiveSession.cpp src/modules/ModuleWorkQueue.cpp src/modules/GccScan.cpp src/modules/ScanCommand.cpp) target_include_directories(vls_protocol PUBLIC "${PROJECT_SOURCE_DIR}/include") -target_link_libraries(vls_protocol PUBLIC Void::Data PRIVATE Void::Unicode) +target_link_libraries(vls_protocol PUBLIC Void::Data PRIVATE Void::Unicode Void::Text Void::Crypto Void::System) target_compile_options(vls_protocol PUBLIC -freflection PRIVATE -Wall -Wextra -Wpedantic) add_executable(vls src/main.cpp) @@ -35,7 +41,18 @@ target_compile_options(vls PRIVATE -Wall -Wextra -Wpedantic) include(GNUInstallDirs) install(TARGETS vls RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") +add_library(vls_gcc_trace STATIC experiments/frontend/gcc-worker/Trace.cpp + src/debug/inspection/ReplaySession.cpp) +target_include_directories(vls_gcc_trace PUBLIC experiments/frontend/gcc-worker) +target_link_libraries(vls_gcc_trace PRIVATE vls_protocol Void::Crypto Void::Unicode) +add_executable(vls-dap src/debug/dap/Main.cpp src/debug/dap/Projection.cpp) +target_link_libraries(vls-dap PRIVATE vls_gcc_trace vls_protocol) +target_compile_options(vls-dap PRIVATE -Wall -Wextra -Wpedantic) +install(TARGETS vls-dap RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") +add_executable(vls_gcc_probe experiments/frontend/gcc-worker/Main.cpp + experiments/frontend/gcc-worker/Leaf.cpp experiments/frontend/gcc-worker/Supervisor.cpp) +target_link_libraries(vls_gcc_probe PRIVATE vls_gcc_trace vls_protocol Void::Crypto Void::System) + if(BUILD_TESTING) - include("${VLS_VOID_TESTING_SCRIPT}") add_subdirectory(tests) endif() diff --git a/README.md b/README.md index 539ae68..e998738 100644 --- a/README.md +++ b/README.md @@ -5,71 +5,143 @@ combines native Void Build System integration, compilation-database compatibilit core IDE features, modules/reflection, and a live/replay metaprogram debugger for Neovim and VS Code. -**Current state:** milestone0 shell implementation. The CLI and stdio LSP lifecycle -are implemented and the ordinary unit/process suites pass. Full JSON conformance -and final shell acceptance are **blocked on VoidLibrary's decimal-support update**. -The capability suite intentionally reports the missing behavior as failures. -This is not yet a usable clangd replacement. +The native server supports stdio lifecycle, UTF-8/UTF-16 negotiation and +incremental document synchronization. It reads native VBS build metadata and +`compile_commands.json` without launching the project compiler. The JSON +capability suite passes on VoidLibrary main, including exact numeric request IDs +and valid numbers outside the parser's machine range. See the +[verification record](docs/agent-workflow/VERIFICATION.md). -Compiler semantics, document synchronization, build providers, indexing, debugging -and editor plugins are planned, not implemented. The shell advertises no semantic -capabilities. See the [27-part roadmap](docs/roadmap/README.md), +The provider and compiler work is in progress. Semantic IDE features, debugging +and editors have separate acceptance gates in the [27-part roadmap](docs/roadmap/README.md), [requirements](docs/roadmap/REQUIREMENTS.md) and [architecture](docs/roadmap/ARCHITECTURE.md). +## Compiler requirements + +Void projects can keep their existing compiler. Building VLS itself has been +verified with stock GCC 16.2. Its C++26 reference tests include VoidLibrary +reflection and module imports. + +The Linux/Nix development profile enables editor diagnostics with unmodified +GCC 16.2. VLS runs the selected translation unit's checked command and sends +`textDocument/publishDiagnostics` as the user edits. It also tracks unsaved +headers and optional headers that appear on disk. Separate module tests feed +GCC dependency scans to the C++ planner. Completion, navigation and editor +scheduling for modules remain in development. + +An experimental GDB adapter observed nested `consteval` return values live on +an unmodified x86-64 Linux GCC 16.2 package. It uses the matching GCC headers +and an internal evaluator symbol. A separate experiment uses a patched frontend +for richer events. Saved GCC recordings can be opened in a DAP client without +a compiler on PATH. Live DAP control remains in development. +See the [stock compiler experiment](tests/corpus/frontend/README.md). + ## Build and test -Requires GCC16+ with C++26 reflection, CMake4+, Ninja and Git. The observed local -environment provides GCC16.2 via `dev cpp-gcc`. On another system, run the underlying -CMake commands in an equivalent toolchain environment; `dev` is a local wrapper. +Use a VoidBuildSystem CLI with its matching SDK, GCC 16.2 with C++26 reflection, +Git and Python 3. The commands below use the local `dev cpp-gcc` environment. +Set `VBS` to the absolute path of your CLI when it is outside that environment's +`PATH`. ```sh -dev cpp-gcc -c cmake -S . -B build/bootstrap -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON +VBS=${VBS:-vbs} +tools/prepare-voidlibrary +dev cpp-gcc -c "$VBS" build --project "$PWD" --build-dir "$PWD/build/native" --profile debug +dev cpp-gcc -c "$VBS" test --project "$PWD" --build-dir "$PWD/build/native" --profile debug +python3 tests/native/Preparation.py +``` + +Preparation fetches VoidLibrary `main` and selects an immutable generation +under `build/voidlibrary`. Run it again to pick up an update. For an explicit +development checkout, use `tools/prepare-voidlibrary --source /path/to/VoidLibrary`. +The selected generation's `provenance.json` records the tested revision and +local input changes. A prepared generation also supports an offline build. + +## Run and install + +```sh +build/native/profiles/debug/out/bin/vls --help +build/native/profiles/debug/out/bin/vls --stdio +dev cpp-gcc -c "$VBS" install --project "$PWD" --build-dir "$PWD/build/native" \ + --profile debug --prefix "$PWD/build/stage" --no-cmake-export +build/stage/bin/vls --version +``` + +The VBS development checkout's dependency-aware install path passed the +staged-executable test. VBS commit `6c225c2` builds and tests VLS, but that +revision's install command fails while resolving `Void::Data`. The native +build executable above is available with either CLI. See the +[verification record](docs/agent-workflow/VERIFICATION.md). + +## Replay a recorded constant evaluation + +Configure a DAP executable with the installed `vls-dap` and the arguments +`--replay /absolute/path/to/recording.vls`. Send a DAP `launch` request. +The included `tests/debug/fixtures/integral-17.vls` opens at the inner +`reflected_value` return of 17. Continue moves to the enclosing `twice` +return of 34 and then to the later recorded values 22 and 44. + +Use Stack Trace and Variables to inspect a return. Loaded Sources exposes +the captured primary text even after its file changes. The recorded function +locations are logical declarations, so clients display the frame name without +jumping to a physical source line. The versioned timeline preserves which +values the compiler actually paused on. The stdio process tests and headless +Neovim session use the same installed executable interface. + +```sh +python3 -B tests/native/DapReplay.py --adapter "$PWD/build/stage/bin/vls-dap" +``` + +## Enable stock GCC editor diagnostics + +Prepare the profile in the same development shell used to build the project. +Pass the project root and the profile's absolute path in the editor's VLS command. + +```sh +dev cpp-gcc -c tools/prepare-gcc-profile --output "$PWD/build/gcc-profile.json" +build/native/profiles/debug/out/bin/vls --stdio \ + --workspace-root "$PWD" --gcc-profile "$PWD/build/gcc-profile.json" +``` + +With the prepared stock occurrence observer, the same profile also enables +hover and definition for verified direct calls: + +```sh +dev cpp-gcc -c tools/prepare-gcc-observer --output "$PWD/build/stock-observer-014/occurrences.so" +dev cpp-gcc -c tools/prepare-gcc-profile --observer "$PWD/build/stock-observer-014/occurrences.so" \ + --output "$PWD/build/gcc-profile.json" +``` + +The launcher sets the workspace's CLI tool-approval list to the profile's single +compiler. This takes precedence over the tool list in a user settings file. +The selected VBS metadata or compilation database +must name the same compiler. The editor supplies the workspace folder and opens +the source document as usual. With no profile the server provides passive build +information and document synchronization. + +The development worker supports one GCC 16.2 Linux/Nix toolchain profile and +analyzes one open translation unit at a time. It captures source bytes under the +launcher root and uses the toolchain's immutable system headers. A client can +request `voidLanguageServer/analysisStatus` with `{"textDocument":{"uri":"…"}}` +to inspect the active context or a compiler message whose editor range could +not be verified. Each checked document has its own result. Project-wide +diagnostics, cross-file navigation and module artifact production remain open. + +With no arguments or with `--stdio`, the server reads Content-Length-framed +UTF-8 JSON on stdin, writes protocol responses on stdout and diagnostics on +stderr. Help and version are standalone options. + +### Comparison build + +The CMake 4/Ninja bootstrap is retained for comparison. A fresh configure +refreshes the fetched revision of VoidLibrary. + +```sh +dev cpp-gcc -c cmake --fresh -S . -B build/bootstrap -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON dev cpp-gcc -c cmake --build build/bootstrap dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure ``` -Default configuration follows VoidLibrary's main branch, as requested. Re-run -configuration to check for upstream updates. The currently observed main revision -still lacks decimal/exponent support; passing configure -and compilation does not mean the full test suite passes. -See [dependency provenance](docs/DEPENDENCIES.md) and -[observed verification](docs/agent-workflow/VERIFICATION.md). - -For explicit development against a local checkout, use a separate output tree: - -```sh -dev cpp-gcc -c cmake -S . -B build/local -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVLS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidLibrary -dev cpp-gcc -c cmake --build build/local -dev cpp-gcc -c ctest --test-dir build/local --output-on-failure -``` - -The override bypasses upstream main and is reported during configuration. The dependency -checkout is never an output directory and must remain unchanged. - -## Run - -```sh -./build/bootstrap/vls --help -./build/bootstrap/vls --version -./build/bootstrap/vls --stdio -``` - -No arguments also starts stdio mode. Send Content-Length-framed UTF-8 JSON through -stdin; stdout contains only protocol messages. Logs/errors go to stderr. -The shell handles initialize/initialized/shutdown/exit, protocol errors and unknown -methods. It returns empty capabilities and no fabricated semantic results. -Header/body/depth limits are8KiB/16MiB/64. Help and version are standalone CLI modes. - -Install the executable into an explicit local prefix after building: - -```sh -dev cpp-gcc -c cmake --install build/bootstrap --prefix /tmp/vls-install -/tmp/vls-install/bin/vls --version -``` - -The development dependency is linked statically; standard compiler/runtime libraries -remain system requirements. Packaging/distribution and licensing are later gates. - ## Development [Current state](docs/agent-workflow/STATE.md) and @@ -80,7 +152,7 @@ Run meaningful tests and obtain independent review of integrated changes. The first usable release includes both live and recorded replay debugging of templates, constraints, constexpr/consteval and reflection, through DAP and custom views in both editors. Frontend/debugger feasibility and native VBS producer work -are explicit gates. CMake bootstraps the repository; native VBS self-build follows. +are explicit gates. Project licensing is intentionally deferred until the backend decision. Local initialization does not authorize commits, pushes, publication or sibling edits. diff --git a/build.cpp b/build.cpp new file mode 100644 index 0000000..48b0233 --- /dev/null +++ b/build.cpp @@ -0,0 +1,203 @@ +#include + +#include +#include + +namespace { + +std::filesystem::path prepared_voidlibrary() { + namespace fs = std::filesystem; + const auto store = fs::current_path() / "build" / "voidlibrary"; + std::error_code ec; + const auto selected = fs::canonical(store / "current", ec); + if (ec) + throw std::runtime_error{"Run tools/prepare-voidlibrary before building VLS."}; + const auto name = selected.filename().string(); + if (selected.parent_path() != store / "sources" || name.size() != 64 || + name.find_first_not_of("0123456789abcdef") != std::string::npos || + !fs::is_regular_file(selected / "provenance.json") || + !fs::is_regular_file(selected / "include/Void/Data/StrictJson.hpp") || + !fs::is_directory(selected / "src/Core") || fs::exists(selected / "build.cpp")) + throw std::runtime_error{"Invalid VoidLibrary generation. Run tools/prepare-voidlibrary."}; + return selected; +} + +} // namespace + +void build(Void::Build::Project &project) { + using namespace Void::Build; + if (project.context().compiler != CompilerFamily::Gcc) + throw std::invalid_argument{"VLS requires GCC 16+ with C++26 reflection."}; + + auto library = project.dependency("VoidLibrary"); + library.path(prepared_voidlibrary().string()) + .native_builder( + {{"VOID_ENABLED_MODULES", "Configuration;Crypto;Data;Text;Unicode;System;Testing"}, + {"BUILD_SHARED_LIBS", false}}); + + auto protocol = project.static_library("vls_protocol"); + protocol.cxx_standard(CxxStandard::Cxx26) + .sources({"src/Protocol/Framing.cpp", + "src/Protocol/Json.cpp", + "src/Documents/DocumentSnapshot.cpp", + "src/Documents/DocumentStore.cpp", + "src/Documents/Position.cpp", + "src/Documents/Uri.cpp", + "src/Workspace/Configuration.cpp", + "src/Workspace/Trust.cpp", + "src/Build/Model.cpp", + "src/Build/ProviderFile.cpp", + "src/Build/CommandImport.cpp", + "src/Build/VbsProvider.cpp", + "src/Build/CompdbProvider.cpp", + "src/DocumentSync.cpp", + "src/WorkspaceSession.cpp", + "src/Server.cpp", + "src/semantic/Diagnostics.cpp", + "src/semantic/SourceCatalog.cpp", + "src/semantic/StockCompiler.cpp", + "src/semantic/EditorDiagnostics.cpp", + "src/semantic/Occurrences.cpp", + "src/scheduler/Scheduler.cpp", + "src/modules/ModuleGraph.cpp", + "src/modules/ArtifactCache.cpp", + "src/modules/GccArtifacts.cpp", + "src/modules/ScheduledArtifacts.cpp", + "src/index/SymbolIndex.cpp", + "src/navigation/Navigation.cpp", + "src/reflection/Provenance.cpp", + "src/features/Completion.cpp", + "src/features/IndexNavigation.cpp", + "src/features/SignatureHelp.cpp", + "src/debug/live/LiveSession.cpp", + "src/modules/ModuleWorkQueue.cpp", + "src/modules/GccScan.cpp", + "src/modules/ScanCommand.cpp"}) + .include_directory("include", Visibility::Public) + .compile_option("-freflection", Visibility::Public) + .link(library.target("Void::Data"), Visibility::Public) + .link(library.target("Void::Unicode")) + .link(library.target("Void::Crypto")) + .link(library.target("Void::Text")) + .link(library.target("Void::System")); + + auto server = project.executable("vls"); + server.cxx_standard(CxxStandard::Cxx26) + .sources({"src/main.cpp"}) + .link(protocol) + .link(library.target("Void::Configuration")) + .install("bin"); + + auto trace = project.static_library("vls_gcc_trace"); + trace.cxx_standard(CxxStandard::Cxx26) + .sources( + {"experiments/frontend/gcc-worker/Trace.cpp", "src/debug/inspection/ReplaySession.cpp"}) + .include_directory("experiments/frontend/gcc-worker", Visibility::Public) + .link(protocol) + .link(library.target("Void::Unicode")) + .link(library.target("Void::Crypto")); + auto dap = project.executable("vls-dap"); + dap.cxx_standard(CxxStandard::Cxx26) + .sources({"src/debug/dap/Main.cpp", "src/debug/dap/Projection.cpp"}) + .link(trace) + .link(protocol) + .install("bin"); + project.executable("vls_gcc_probe") + .cxx_standard(CxxStandard::Cxx26) + .sources({"experiments/frontend/gcc-worker/Main.cpp", + "experiments/frontend/gcc-worker/Leaf.cpp", + "experiments/frontend/gcc-worker/Supervisor.cpp"}) + .link(trace) + .link(protocol) + .link(library.target("Void::Crypto")) + .link(library.target("Void::System")); + + auto suite = [&](const char *name, const SourceSet &sources) { + auto target = project.test(name); + target.cxx_standard(CxxStandard::Cxx26) + .sources(sources) + .link(protocol) + .link(library.target("Void::Testing")); + return target; + }; + auto unit = + suite("vls_unit_tests", {"tests/FramingTests.cpp", "tests/JsonTests.cpp", + "tests/LifecycleTests.cpp", "tests/ProtocolEncodingTests.cpp"}); + auto numbers = suite("vls_json_capabilities", {"tests/JsonCapabilities.cpp"}); + auto process = + suite("vls_process_tests", {"tests/ProcessTests.cpp", "tests/ProviderProcessTests.cpp"}); + auto documents = suite("vls_document_tests", {"tests/documents/DocumentTests.cpp", + "tests/documents/LongLineTests.cpp", + "tests/documents/BoundInputTests.cpp"}); + auto workspace = suite("vls_workspace_tests", {"tests/workspace/WorkspaceTests.cpp", + "tests/workspace/ProviderSessionTests.cpp", + "tests/workspace/SemanticLeaseTests.cpp"}); + auto model = suite("vls_build_model_tests", {"tests/providers/ModelTests.cpp"}); + auto diagnostics = suite("vls_diagnostic_tests", {"tests/semantic/DiagnosticTests.cpp", + "tests/semantic/SourceCatalogTests.cpp", + "tests/semantic/OccurrenceTests.cpp"}); + auto modules = + suite("vls_module_tests", + {"tests/modules/ModuleGraphTests.cpp", "tests/modules/ArtifactCacheTests.cpp", + "tests/modules/ModuleWorkQueueTests.cpp", "tests/modules/ScanCommandTests.cpp"}); + auto scheduler_tests = suite("vls_scheduler_tests", {"tests/scheduler/SchedulerTests.cpp"}); + auto index_tests = suite("vls_index_tests", {"tests/index/SymbolIndexTests.cpp"}); + auto navigation_tests = suite("vls_navigation_tests", {"tests/navigation/NavigationTests.cpp"}); + auto reflection_tests = suite("vls_reflection_tests", {"tests/reflection/ProvenanceTests.cpp"}); + auto feature_tests = suite("vls_feature_tests", {"tests/features/CompletionTests.cpp", + "tests/features/IndexNavigationTests.cpp", + "tests/features/SignatureHelpTests.cpp"}); + auto live_worker = project.executable("vls_live_worker_fixture"); + live_worker.cxx_standard(CxxStandard::Cxx26) + .sources({"tests/debug/LiveWorkerFixture.cpp"}) + .link(protocol); + auto live_tests = suite("vls_live_tests", + {"tests/debug/LiveSessionTests.cpp", "tests/debug/LiveDapTests.cpp"}); + live_tests.link(library.target("Void::System")).depends_on(live_worker).depends_on(dap); + project.executable("vls_gcc_diagnostic_fixture") + .cxx_standard(CxxStandard::Cxx26) + .sources({"tests/semantic/GccDiagnosticFixture.cpp"}) + .link(protocol); + project.executable("vls_module_scan_fixture") + .cxx_standard(CxxStandard::Cxx26) + .sources({"tests/modules/GccScanFixture.cpp"}) + .link(protocol); + project.executable("vls_module_artifact_fixture") + .cxx_standard(CxxStandard::Cxx26) + .sources({"tests/modules/ModuleArtifactFixture.cpp"}) + .link(protocol) + .link(library.target("Void::System")); + auto trace_tests = + suite("vls_trace_tests", {"tests/debug/TraceTests.cpp", "tests/debug/RecordingTests.cpp"}); + trace_tests.link(trace); + auto dap_tests = suite("vls_dap_tests", {"tests/debug/DapReplayTests.cpp"}); + dap_tests.link(trace).link(library.target("Void::System")).depends_on(dap); + auto providers = suite("vls_provider_tests", {"tests/providers/ProviderFileTests.cpp", + "tests/providers/VbsProviderTests.cpp", + "tests/providers/CompdbProviderTests.cpp", + "tests/providers/CommandImportTests.cpp"}); + numbers.link(library.target("Void::System")).depends_on(server); + process.link(library.target("Void::System")).depends_on(server); + + project.test("vls_test_registration") + .cxx_standard(CxxStandard::Cxx26) + .sources({"tests/NativeRegistration.cpp"}) + .link(library.target("Void::System")) + .depends_on(unit) + .depends_on(numbers) + .depends_on(process) + .depends_on(documents) + .depends_on(workspace) + .depends_on(model) + .depends_on(diagnostics) + .depends_on(modules) + .depends_on(trace_tests) + .depends_on(dap_tests) + .depends_on(providers) + .depends_on(scheduler_tests) + .depends_on(index_tests) + .depends_on(navigation_tests) + .depends_on(reflection_tests) + .depends_on(feature_tests) + .depends_on(live_tests); +} diff --git a/build.profiles.cpp b/build.profiles.cpp new file mode 100644 index 0000000..6d22726 --- /dev/null +++ b/build.profiles.cpp @@ -0,0 +1,12 @@ +#include + +void profiles(Void::Build::Profiles &descriptions) { + using namespace Void::Build; + descriptions = default_profiles(); + descriptions.define({ + .name = "sanitized", + .compile_options = {"-fno-omit-frame-pointer", "-fno-sanitize-recover=undefined"}, + .parent = "debug", + .sanitizers = {Sanitizer::Address, Sanitizer::Undefined}, + }); +} diff --git a/clients/neovim/README.md b/clients/neovim/README.md new file mode 100644 index 0000000..47f9495 --- /dev/null +++ b/clients/neovim/README.md @@ -0,0 +1,55 @@ +# VoidLanguageServer Neovim client + +Thin Neovim LSP and replay-DAP integration for the installed `vls` and +`vls-dap`. All language, build and debugger semantics stay in the C++ server; +this plugin only starts processes, forwards user actions and renders bounded +replies. + +## Setup + +Add this directory to `runtimepath` (for example with your plugin manager), or +copy `plugin/` and `lua/` into a Neovim config directory. Neovim 0.12.6 or newer +is tested. `nvim-dap` is optional and only needed for replay. + +```lua +require("vls").setup({ + server = "/absolute/path/to/vls", -- default: vls on PATH + dap_adapter = "/absolute/path/to/vls-dap", -- default: vls-dap on PATH + gcc_profile = nil, -- absolute prepared GCC profile + provider = nil, -- auto, vbs, compdb or none +}) +``` + +## Commands + +| Command | Action | +| --- | --- | +| `:VlsStart` | Start the server for the current buffer and workspace root. | +| `:VlsStatus` | Request `voidLanguageServer/providerStatus`. | +| `:VlsAnalysisStatus` | Request `voidLanguageServer/analysisStatus`. | +| `:VlsReplay {trace}` | Launch `vls-dap --replay` on an absolute recording. | +| `:VlsSession` | Subscribe to the active replay session and generation. | +| `:VlsTimeline [start] [count]` | Render a bounded timeline page. | +| `:VlsFrames [start] [count]` | Render a bounded frame page. | +| `:VlsSource` | Render the captured source of the active replay. | +| `:VlsStop` | Terminate the replay. | +| `:VlsRename {name}` | Request a guarded rename and apply it transactionally. | + +Replies from a generation older than the subscribed one are rejected instead +of being rendered. Rename edits are validated for every buffer before any is +touched; if a buffer write fails, all already-changed buffers are restored +exactly and the transaction reports the failure. + +## Acceptance + +```sh +VLS_SERVER="$PWD/build/native/profiles/debug/out/bin/vls" \ +VLS_DAP="$PWD/build/native/profiles/debug/out/bin/vls-dap" \ +VLS_TRACE="$PWD/tests/debug/fixtures/integral-17.vls" \ +VLS_NVIM_DAP="$PWD/build/dap-evidence/nvim-dap" \ +nvim --headless -u NONE -i NONE -l tests/native/NeovimClient.lua +``` + +The test uses a temporary workspace, does not read or write user +configuration, and checks LSP status, a real replay session, timeline paging, +captured source, stale-generation rejection and shutdown. diff --git a/clients/neovim/lua/vls/init.lua b/clients/neovim/lua/vls/init.lua new file mode 100644 index 0000000..647fb54 --- /dev/null +++ b/clients/neovim/lua/vls/init.lua @@ -0,0 +1,367 @@ +local M = {} + +local defaults = { + server = nil, + dap_adapter = nil, + gcc_profile = nil, + provider = nil, +} + +local state = { config = {}, replay = nil } + +function M.setup(options) + state.config = vim.tbl_extend("force", defaults, options or {}) +end + +local function config() + return state.config +end + +local function absolute(path) + return type(path) == "string" and vim.startswith(path, "/") +end + +local function executable(name, explicit) + local path = explicit or vim.fn.exepath(name) + if path == nil or path == "" then + return nil, name .. " is not on PATH" + end + if not absolute(path) then + return nil, name .. " did not resolve to an absolute path" + end + return path +end + +local function workspace_root(bufnr) + local name = vim.api.nvim_buf_get_name(bufnr) + if name == "" then + return vim.fn.getcwd() + end + local markers = { ".git", "vbs.lock", "compile_commands.json", "build.cpp" } + return vim.fs.root(name, markers) or vim.fn.fnamemodify(name, ":p:h") +end + +local function client_for(bufnr) + for _, client in ipairs(vim.lsp.get_clients({ bufnr = bufnr })) do + if client.name == "VoidLanguageServer" then + return client + end + end + return nil +end + +function M.start(bufnr) + bufnr = bufnr or vim.api.nvim_get_current_buf() + local server, err = executable("vls", config().server) + if not server then + return nil, err + end + local root = workspace_root(bufnr) + local cmd = { server, "--stdio", "--workspace-root", root } + if config().provider then + vim.list_extend(cmd, { "--provider", config().provider }) + end + if config().gcc_profile then + if not absolute(config().gcc_profile) then + return nil, "gcc_profile must be an absolute path" + end + vim.list_extend(cmd, { "--gcc-profile", config().gcc_profile }) + end + local id = vim.lsp.start({ name = "VoidLanguageServer", cmd = cmd, root_dir = root }, + { bufnr = bufnr }) + if not id then + return nil, "could not start VoidLanguageServer" + end + return vim.lsp.get_client_by_id(id) +end + +local function request_sync(bufnr, method, params) + bufnr = bufnr or vim.api.nvim_get_current_buf() + local client = client_for(bufnr) + if not client then + return nil, "no VoidLanguageServer attached to this buffer" + end + local reply = client:request_sync(method, params, 5000, bufnr) + if not reply then + return nil, method .. " timed out" + end + if reply.err then + return nil, vim.inspect(reply.err) + end + return reply.result +end + +function M.status(bufnr) + bufnr = bufnr or vim.api.nvim_get_current_buf() + local client = client_for(bufnr) + if not client then + return nil, "no VoidLanguageServer attached to this buffer" + end + return request_sync(bufnr, "voidLanguageServer/providerStatus", { + textDocument = { uri = vim.uri_from_bufnr(bufnr) }, + workspaceUri = vim.uri_from_fname(client.config.root_dir), + }) +end + +function M.analysis_status(bufnr) + bufnr = bufnr or vim.api.nvim_get_current_buf() + return request_sync(bufnr, "voidLanguageServer/analysisStatus", { + textDocument = { uri = vim.uri_from_bufnr(bufnr) }, + }) +end + +local function dap() + local ok, module = pcall(require, "dap") + if ok then + return module + end + return nil +end + +function M.replay(trace) + if not absolute(trace) then + return nil, "an absolute trace path is required" + end + if vim.fn.filereadable(trace) ~= 1 then + return nil, "trace is not readable: " .. trace + end + local adapter, err = executable("vls-dap", config().dap_adapter) + if not adapter then + return nil, err + end + local dap_module = dap() + if not dap_module then + return nil, "nvim-dap is not installed" + end + local name = "vls-replay" + dap_module.adapters[name] = { type = "executable", command = adapter, + args = { "--replay", trace } } + dap_module.configurations.cpp = dap_module.configurations.cpp or {} + for index = #dap_module.configurations.cpp, 1, -1 do + if dap_module.configurations.cpp[index].type == name then + table.remove(dap_module.configurations.cpp, index) + end + end + local configuration = { type = name, request = "launch", + name = "VLS replay " .. vim.fn.fnamemodify(trace, ":t") } + table.insert(dap_module.configurations.cpp, configuration) + state.replay = { trace = trace } + dap_module.run(configuration) + return state.replay +end + +local function session() + local dap_module = dap() + if not dap_module then + return nil + end + return dap_module.session() +end + +local function request(method, arguments) + local active = session() + if not active then + return nil, "no active replay session" + end + local done, failure, body = false, nil, nil + active:request(method, arguments, function(err, result) + failure, body, done = err, result, true + end) + if not vim.wait(5000, function() return done end, 10) then + return nil, method .. " timed out" + end + if failure then + return nil, vim.inspect(failure) + end + return body +end + +function M.session() + local reply, err = request("vls/session") + if not reply then + return nil, err + end + state.replay = state.replay or {} + state.replay.schemaVersion = reply.schemaVersion + state.replay.sessionId = reply.sessionId + state.replay.generation = reply.generation + return reply +end + +local function current() + local active = state.replay + if not active or not active.generation then + return nil, "subscribe with :VlsSession first" + end + return active +end + +function M.timeline(start, count) + local active, err = current() + if not active then + return nil, err + end + local page, failure = request("vls/timeline", { + schemaVersion = active.schemaVersion, + sessionId = active.sessionId, + generation = active.generation, + start = start or 0, + count = count or 20, + }) + if not page then + return nil, failure + end + if page.sessionId ~= active.sessionId or page.generation ~= active.generation then + return nil, "stale replay generation" + end + return page +end + +function M.frames(start, count) + local active, err = current() + if not active then + return nil, err + end + local page, failure = request("vls/frames", { + schemaVersion = active.schemaVersion, + sessionId = active.sessionId, + generation = active.generation, + start = start or 0, + count = count or 20, + }) + if not page then + return nil, failure + end + if page.sessionId ~= active.sessionId or page.generation ~= active.generation then + return nil, "stale replay generation" + end + return page +end + +function M.source() + local active, err = current() + if not active then + return nil, err + end + local reply, failure = request("source", { sourceReference = 1 }) + if not reply then + return nil, failure + end + return reply.content +end + +function M.stop() + local dap_module = dap() + if dap_module and dap_module.session() then + dap_module.terminate() + end + state.replay = nil +end + +function M.render(title, lines) + local buffer = vim.api.nvim_create_buf(false, true) + vim.api.nvim_buf_set_lines(buffer, 0, -1, false, lines) + vim.bo[buffer].bufhidden = "wipe" + vim.bo[buffer].filetype = "vls-inspection" + vim.api.nvim_buf_set_name(buffer, title .. " " .. os.date("%H:%M:%S")) + vim.cmd.split() + vim.api.nvim_win_set_buf(0, buffer) + return buffer +end + +local function before(left, right) + if left.line ~= right.line then + return left.line > right.line + end + return left.character > right.character +end + +-- Applies an LSP `changes` map transactionally. Every range is validated +-- before any buffer is touched; an application failure restores the exact +-- pre-edit lines and modified state of every buffer already changed. +function M.apply_workspace_edit(changes) + if type(changes) ~= "table" then + return nil, "no workspace edit changes" + end + local plan = {} + for uri, edits in pairs(changes) do + if type(edits) ~= "table" or #edits == 0 then + return nil, "empty edit list for " .. uri + end + local bufnr = vim.uri_to_bufnr(uri) + if not vim.api.nvim_buf_is_loaded(bufnr) then + vim.fn.bufload(bufnr) + end + local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) + local sorted = vim.deepcopy(edits) + table.sort(sorted, function(left, right) + return before(left.range.start, right.range.start) + end) + for _, edit in ipairs(sorted) do + local first, last = edit.range.start, edit.range["end"] + if first.line < 0 or first.line >= #lines or last.line < first.line or + last.line >= #lines or first.character < 0 or last.character < 0 or + first.character > #lines[first.line + 1] or + (last.line == first.line and last.character < first.character) then + return nil, "edit range is outside the buffer: " .. uri + end + if type(edit.newText) ~= "string" then + return nil, "edit text is not a string: " .. uri + end + end + plan[#plan + 1] = { bufnr = bufnr, uri = uri, lines = lines, + modified = vim.bo[bufnr].modified, edits = sorted } + end + table.sort(plan, function(left, right) return left.uri < right.uri end) + for _, item in ipairs(plan) do + if not vim.bo[item.bufnr].modifiable then + return nil, "buffer is not modifiable: " .. item.uri + end + end + local applied = {} + local ok, failure = pcall(function() + for _, item in ipairs(plan) do + applied[#applied + 1] = item + for _, edit in ipairs(item.edits) do + vim.api.nvim_buf_set_text(item.bufnr, edit.range.start.line, + edit.range.start.character, edit.range["end"].line, + edit.range["end"].character, { edit.newText }) + end + end + end) + if ok then + return true + end + for _, item in ipairs(applied) do + vim.api.nvim_buf_set_lines(item.bufnr, 0, -1, false, item.lines) + vim.bo[item.bufnr].modified = item.modified + end + return nil, tostring(failure) +end + +-- Requests a guarded rename from the server and applies it transactionally. +function M.rename(new_name, bufnr) + bufnr = bufnr or vim.api.nvim_get_current_buf() + local client = client_for(bufnr) + if not client then + return nil, "no VoidLanguageServer attached to this buffer" + end + local cursor = vim.api.nvim_win_get_cursor(0) + local reply = client:request_sync("textDocument/rename", { + textDocument = { uri = vim.uri_from_bufnr(bufnr) }, + position = { line = cursor[1] - 1, character = cursor[2] }, + newName = new_name, + }, 5000, bufnr) + if not reply then + return nil, "textDocument/rename timed out" + end + if reply.err then + return nil, (reply.err.message or vim.inspect(reply.err)) + end + if not reply.result or not reply.result.changes then + return nil, "the server returned no rename changes" + end + return M.apply_workspace_edit(reply.result.changes) +end + +return M diff --git a/clients/neovim/plugin/vls.lua b/clients/neovim/plugin/vls.lua new file mode 100644 index 0000000..be8f2c8 --- /dev/null +++ b/clients/neovim/plugin/vls.lua @@ -0,0 +1,92 @@ +if vim.g.loaded_vls then + return +end +vim.g.loaded_vls = 1 + +local function report(subject, result, err) + if err then + vim.notify("VLS: " .. err, vim.log.levels.ERROR) + return + end + vim.notify(subject .. "\n" .. vim.inspect(result), vim.log.levels.INFO) +end + +vim.api.nvim_create_user_command("VlsStart", function() + local client, err = require("vls").start() + report("VoidLanguageServer started", + client and { id = client.id, root = client.config.root_dir } or nil, err) +end, { desc = "Start VoidLanguageServer for the current buffer" }) + +vim.api.nvim_create_user_command("VlsStatus", function() + report("VoidLanguageServer provider status", require("vls").status()) +end, { desc = "Request provider status for the current document" }) + +vim.api.nvim_create_user_command("VlsAnalysisStatus", function() + report("VoidLanguageServer analysis status", require("vls").analysis_status()) +end, { desc = "Request semantic analysis status for the current document" }) + +vim.api.nvim_create_user_command("VlsReplay", function(options) + local trace = vim.fn.fnamemodify(options.args, ":p") + report("VoidLanguageServer replay", require("vls").replay(trace)) +end, { nargs = 1, complete = "file", desc = "Replay an absolute VLS recording" }) + +vim.api.nvim_create_user_command("VlsSession", function() + report("VoidLanguageServer replay session", require("vls").session()) +end, { desc = "Subscribe to the active replay session and generation" }) + +vim.api.nvim_create_user_command("VlsTimeline", function(options) + local fields = vim.split(options.args, "%s+", { trimempty = true }) + local page, err = require("vls").timeline(tonumber(fields[1]), tonumber(fields[2])) + if err then + report("VoidLanguageServer timeline", nil, err) + return + end + local lines = { string.format("session %s generation %d total %d", + page.sessionId, page.generation, page.total) } + for _, event in ipairs(page.events) do + table.insert(lines, string.format("%d %s%s", event.sequence, event.kind, + event.acknowledgedAction and + string.format(" stop=%d action=%s", event.acknowledgedStop, + event.acknowledgedAction) or "")) + end + require("vls").render("VLS timeline", lines) +end, { nargs = "*", desc = "Show a bounded timeline page: :VlsTimeline [start] [count]" }) + +vim.api.nvim_create_user_command("VlsFrames", function(options) + local fields = vim.split(options.args, "%s+", { trimempty = true }) + local page, err = require("vls").frames(tonumber(fields[1]), tonumber(fields[2])) + if err then + report("VoidLanguageServer frames", nil, err) + return + end + local lines = { string.format("session %s generation %d total %d", + page.sessionId, page.generation, page.total) } + for _, frame in ipairs(page.frames) do + table.insert(lines, string.format("%s %s", tostring(frame.id), + tostring(frame.name))) + end + require("vls").render("VLS frames", lines) +end, { nargs = "*", desc = "Show a bounded frame page: :VlsFrames [start] [count]" }) + +vim.api.nvim_create_user_command("VlsSource", function() + local content, err = require("vls").source() + if err then + report("VoidLanguageServer source", nil, err) + return + end + require("vls").render("VLS captured source", vim.split(content, "\n", { plain = true })) +end, { desc = "Show the captured source of the active replay" }) + +vim.api.nvim_create_user_command("VlsStop", function() + require("vls").stop() + vim.notify("VLS: replay stopped", vim.log.levels.INFO) +end, { desc = "Stop the active replay session" }) + +vim.api.nvim_create_user_command("VlsRename", function(options) + local ok, err = require("vls").rename(options.args) + if not ok then + vim.notify("VLS: " .. err, vim.log.levels.ERROR) + else + vim.notify("VLS: rename applied", vim.log.levels.INFO) + end +end, { nargs = 1, desc = "Rename the symbol at the cursor through the server" }) diff --git a/clients/vscode/README.md b/clients/vscode/README.md new file mode 100644 index 0000000..29a5dfb --- /dev/null +++ b/clients/vscode/README.md @@ -0,0 +1,51 @@ +# VoidLanguageServer VS Code client + +Thin VS Code extension for the installed `vls` language server and the +`vls-dap` replay adapter. All language, build and debugger semantics stay in +the C++ server. + +## Build + +Node and npm are development prerequisites. Dependencies are fetched only by +this explicit step, never by the acceptance test: + +```sh +cd clients/vscode +npm install +npm run compile +``` + +## Use + +| Setting | Meaning | +| --- | --- | +| `vls.serverPath` | Absolute path to `vls` (default: `vls` on `PATH`). | +| `vls.dapPath` | Absolute path to `vls-dap` (default: `vls-dap` on `PATH`). | +| `vls.gccProfile` | Absolute prepared stock GCC profile for editor diagnostics. | +| `vls.provider` | Build-context preference: `auto`, `vbs`, `compdb` or `none`. | + +Commands: `VLS: Start Language Server`, `VLS: Provider Status`, +`VLS: Analysis Status`, `VLS: Replay Recording`, `VLS: Stop Language Server`. +The C++ rename provider forwards `prepareRename`/`rename` to the server; the +exported `applyRename` applies an LSP `changes` map through one WorkspaceEdit +after checking the document versions captured at preparation, so a stale plan +is refused without partial edits. +The `VLS replay` debug configuration launches an absolute recording; the +extension renders only bounded server replies and rejects a stale +session/generation. + +## Acceptance + +The test runs a disposable extension host with temporary user-data and +extensions directories; it does not touch the user's profile. + +```sh +python3 -B tests/native/VscodeClient.py \ + --server "$PWD/build/native/profiles/debug/out/bin/vls" \ + --adapter "$PWD/build/native/profiles/debug/out/bin/vls-dap" \ + --trace "$PWD/tests/debug/fixtures/integral-17.vls" +``` + +On Nix, the `code` launcher detaches from the terminal, so the test invokes the +application binary (`lib/vscode/code`) directly to keep the extension host's +exit status and output. diff --git a/clients/vscode/package-lock.json b/clients/vscode/package-lock.json new file mode 100644 index 0000000..8c13572 --- /dev/null +++ b/clients/vscode/package-lock.json @@ -0,0 +1,162 @@ +{ + "name": "vls-vscode", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "vls-vscode", + "version": "0.0.1", + "dependencies": { + "vscode-languageclient": "^12.0.0" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "@types/vscode": "^1.146.0", + "typescript": "^5.7.0" + }, + "engines": { + "vscode": "^1.91.0" + } + }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/@types/node": { + "version": "24.19.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.4.tgz", + "integrity": "sha512-s04odlR3ksJrLu7QLi+pddkWLD0RmSbcP9KuWn2/ozQKAp/YgwBC/6x9kJj8yAzZnGPfxePm7zm7nysVPCRagw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@types/vscode": { + "version": "1.146.0", + "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.146.0.tgz", + "integrity": "sha512-OtU25faeM997QQsW+D07FN9cX06j+EEI4aQaPw/UO3HWlCM39N1W7fG8ewhdZKluut31KffyMsmDzJzgMu6t8Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/brace-expansion": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.1.2.tgz", + "integrity": "sha512-ELhY3JEerIBbhgW+rh0/8glkZAaMqn1x3BAvp3yTULSEGozMK/5PT6WTdBgsdvJqwwmv7MAQNOydfYbvK1Vgfw==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/minimatch": { + "version": "11.0.10", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.10.tgz", + "integrity": "sha512-L3/cjhQ5E6lft0VCp/2mO3Ic74RnutKy3rz7iGwp/6w1hKcO262g2rbfacFyw6eBig5OdI0nu5PpuA0/WQs9Tw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vscode-jsonrpc": { + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-10.0.2.tgz", + "integrity": "sha512-U6K7wa1t8jTZf7eoHJLKSNdHE0oi9r/+/4TSXWPSLQ2FSQVMYLR5TvzQHrYjwW/lLjq0eTm+pi8vWz4jSV7o4w==", + "license": "MIT", + "engines": { + "node": ">=14.17.0" + } + }, + "node_modules/vscode-languageclient": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-12.0.0.tgz", + "integrity": "sha512-lDxVFl/sr++Mf/v9oY9Kh9Ihh+241zkVijtjJ1Q9w4QSeOkjojKO3Teg5bNPWHZU1zXbaI9/OTcajYjDZUWPEA==", + "license": "MIT", + "dependencies": { + "minimatch": "^11.0.9", + "semver": "^7.8.1", + "vscode-languageserver-protocol": "3.18.7", + "vscode-languageserver-textdocument": "1.0.16" + }, + "engines": { + "vscode": "^1.91.0" + } + }, + "node_modules/vscode-languageserver-protocol": { + "version": "3.18.7", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.18.7.tgz", + "integrity": "sha512-5oItSZDTTehe0zXzwJCFUMso6RfUb2FWVTFfQxAesV3nTbkY1hjW3O6q8872M9TACEXFcALaU5xU37sGudYI8g==", + "license": "MIT", + "dependencies": { + "vscode-jsonrpc": "10.0.2", + "vscode-languageserver-types": "3.18.6" + } + }, + "node_modules/vscode-languageserver-textdocument": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.16.tgz", + "integrity": "sha512-qeNEuOi9a3qkqRf7Gfez2WL2VwlBTLCNekHBGO9kxPVUp9XuY15yfTJ9jwvOwKI0I2MhUUfZq95NSp+LK1CLQg==", + "license": "MIT" + }, + "node_modules/vscode-languageserver-types": { + "version": "3.18.6", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.18.6.tgz", + "integrity": "sha512-DEDtik4YupS+nOg4JxqJ2H5ec/m4tTD9a5mGcBVGYkQKZQo1AIF3ZToiP8+A0kUzyhyqX5dMnPDEnhtmzts7GA==", + "license": "MIT" + } + } +} diff --git a/clients/vscode/package.json b/clients/vscode/package.json new file mode 100644 index 0000000..7abe6e3 --- /dev/null +++ b/clients/vscode/package.json @@ -0,0 +1,130 @@ +{ + "name": "vls-vscode", + "displayName": "VoidLanguageServer", + "description": "Thin VS Code client for the VoidLanguageServer LSP and replay DAP.", + "publisher": "vls-local", + "version": "0.0.1", + "private": true, + "engines": { + "vscode": "^1.91.0" + }, + "categories": [ + "Programming Languages", + "Debuggers" + ], + "activationEvents": [ + "onLanguage:cpp", + "onCommand:vls.start" + ], + "main": "./out/extension.js", + "contributes": { + "commands": [ + { + "command": "vls.start", + "title": "VLS: Start Language Server" + }, + { + "command": "vls.providerStatus", + "title": "VLS: Provider Status" + }, + { + "command": "vls.analysisStatus", + "title": "VLS: Analysis Status" + }, + { + "command": "vls.replay", + "title": "VLS: Replay Recording" + }, + { + "command": "vls.stop", + "title": "VLS: Stop Language Server" + } + ], + "configuration": { + "title": "VoidLanguageServer", + "properties": { + "vls.serverPath": { + "type": "string", + "default": "", + "description": "Absolute path to the vls executable (default: vls on PATH)." + }, + "vls.dapPath": { + "type": "string", + "default": "", + "description": "Absolute path to the vls-dap executable (default: vls-dap on PATH)." + }, + "vls.gccProfile": { + "type": "string", + "default": "", + "description": "Absolute prepared stock GCC profile for editor diagnostics." + }, + "vls.provider": { + "type": "string", + "enum": [ + "", + "auto", + "vbs", + "compdb", + "none" + ], + "default": "", + "description": "Build-context provider preference." + } + } + }, + "debuggers": [ + { + "type": "vls-replay", + "label": "VLS replay", + "languages": [ + "cpp" + ], + "configurationAttributes": { + "launch": { + "properties": { + "trace": { + "type": "string", + "description": "Absolute path to a VLS recording.", + "default": "" + } + }, + "required": [ + "trace" + ] + } + }, + "initialConfigurations": [ + { + "type": "vls-replay", + "request": "launch", + "name": "VLS replay", + "trace": "" + } + ], + "configurationSnippets": [ + { + "label": "VLS: replay a recording", + "body": { + "type": "vls-replay", + "request": "launch", + "name": "VLS replay ${1:name}", + "trace": "^\"\\${2:/absolute/path/to/recording.vls}\"" + } + } + ] + } + ] + }, + "scripts": { + "compile": "tsc -p .", + "test": "node ./out/test/run.js" + }, + "dependencies": { + "vscode-languageclient": "^12.0.0" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "@types/vscode": "^1.146.0", + "typescript": "^5.7.0" + } +} diff --git a/clients/vscode/src/extension.ts b/clients/vscode/src/extension.ts new file mode 100644 index 0000000..42003b7 --- /dev/null +++ b/clients/vscode/src/extension.ts @@ -0,0 +1,269 @@ +import * as path from 'path'; +import * as vscode from 'vscode'; +import { LanguageClient, LanguageClientOptions, ServerOptions } from 'vscode-languageclient/node'; + +let client: LanguageClient | undefined; +let output: vscode.LogOutputChannel; + +function settings(): vscode.WorkspaceConfiguration { + return vscode.workspace.getConfiguration('vls'); +} + +function rootFor(document?: vscode.TextDocument): string | undefined { + const uri = document?.uri ?? vscode.window.activeTextEditor?.document.uri; + if (uri) { + const folder = vscode.workspace.getWorkspaceFolder(uri); + if (folder) { + return folder.uri.fsPath; + } + if (uri.scheme === 'file') { + return path.dirname(uri.fsPath); + } + } + return vscode.workspace.workspaceFolders?.[0]?.uri.fsPath; +} + +async function start(): Promise { + await stop(); + const server = settings().get('serverPath') || 'vls'; + const root = rootFor(); + if (!root) { + throw new Error('open a C++ document or a workspace folder first'); + } + const args = ['--stdio', '--workspace-root', root]; + const provider = settings().get('provider'); + if (provider) { + args.push('--provider', provider); + } + const profile = settings().get('gccProfile'); + if (profile) { + if (!path.isAbsolute(profile)) { + throw new Error('vls.gccProfile must be an absolute path'); + } + args.push('--gcc-profile', profile); + } + const serverOptions: ServerOptions = { command: server, args, options: { cwd: root } }; + const clientOptions: LanguageClientOptions = { + documentSelector: [ + { scheme: 'file', language: 'cpp' }, + { scheme: 'file', language: 'c' }, + ], + outputChannel: output, + }; + client = new LanguageClient('vls', 'VoidLanguageServer', serverOptions, clientOptions); + await client.start(); +} + +async function stop(): Promise { + if (client) { + await client.stop(); + client = undefined; + } +} + +async function requestStatus(method: string): Promise { + if (!client || !client.isRunning()) { + throw new Error('VoidLanguageServer is not running'); + } + const document = vscode.window.activeTextEditor?.document; + if (!document) { + throw new Error('no active document'); + } + const params: Record = { textDocument: { uri: document.uri.toString() } }; + if (method === 'voidLanguageServer/providerStatus') { + const root = rootFor(document); + if (!root) { + throw new Error('no workspace root for the active document'); + } + params.workspaceUri = vscode.Uri.file(root).toString(); + } + const reply = await client.sendRequest(method, params); + output.appendLine(`${method}: ${JSON.stringify(reply, null, 2)}`); + output.show(true); + return reply; +} + +async function replay(trace?: string): Promise { + let selected = trace; + if (!selected) { + const choice = await vscode.window.showOpenDialog({ + canSelectFiles: true, + canSelectMany: false, + openLabel: 'Replay recording', + }); + selected = choice?.[0]?.fsPath; + } + if (!selected) { + return; + } + if (!path.isAbsolute(selected)) { + throw new Error('the trace path must be absolute'); + } + const started = await vscode.debug.startDebugging(vscode.workspace.workspaceFolders?.[0], { + type: 'vls-replay', + request: 'launch', + name: `VLS replay ${path.basename(selected)}`, + trace: selected, + }); + if (!started) { + throw new Error('could not start the VLS replay session'); + } +} + +export interface RenameChange { + range: { start: { line: number; character: number }; end: { line: number; character: number } }; + newText: string; +} +export type RenameChanges = Record; + +export interface RenamePlanInput { + changes: RenameChanges; + // Document versions observed when the rename was requested. A mismatch + // means the plan is stale and must not be applied. + versions?: Record; +} + +// Applies an LSP `changes` map through one WorkspaceEdit. Ranges are validated +// and every document version is rechecked immediately before application; an +// injected failure leaves no partial edits because VS Code applies the edit +// transactionally. +export async function applyRename(input: RenamePlanInput): + Promise<{ applied: boolean; reason?: string }> { + const edit = new vscode.WorkspaceEdit(); + const prepared = new Map(); + for (const [uri, edits] of Object.entries(input.changes)) { + if (!edits.length) { + return { applied: false, reason: `empty edit list for ${uri}` }; + } + const document = await vscode.workspace.openTextDocument(vscode.Uri.parse(uri)); + const expected = input.versions?.[uri]; + if (expected !== undefined && expected !== document.version) { + return { applied: false, reason: `document changed after preparation: ${uri}` }; + } + prepared.set(uri, { version: document.version, text: document.getText() }); + for (const change of edits) { + const start = new vscode.Position(change.range.start.line, change.range.start.character); + const end = new vscode.Position(change.range.end.line, change.range.end.character); + const range = new vscode.Range(start, end); + if (change.range.start.line >= document.lineCount || + change.range.end.line >= document.lineCount || + document.validateRange(range).end.isBefore(end) || + end.isBefore(start) || typeof change.newText !== "string") { + return { applied: false, reason: `edit range is outside the document: ${uri}` }; + } + edit.replace(document.uri, range, change.newText); + } + } + for (const [uri, expected] of prepared) { + const document = await vscode.workspace.openTextDocument(vscode.Uri.parse(uri)); + if (document.version !== expected.version || document.getText() !== expected.text) { + return { applied: false, reason: `document changed after preparation: ${uri}` }; + } + } + return await vscode.workspace.applyEdit(edit) + ? { applied: true } + : { applied: false, reason: "the workspace edit was rejected" }; +} + +function registerRename(context: vscode.ExtensionContext): void { + context.subscriptions.push(vscode.languages.registerRenameProvider( + { scheme: "file", language: "cpp" }, + { + async prepareRename(document, position) { + if (!client || !client.isRunning()) { + throw new Error("VoidLanguageServer is not running"); + } + const reply = await client.sendRequest("textDocument/prepareRename", { + textDocument: { uri: document.uri.toString() }, + position: { line: position.line, character: position.character }, + }); + if (!reply || !reply.range) { + throw new Error("no symbol at the requested position"); + } + return new vscode.Range(reply.range.start.line, reply.range.start.character, + reply.range.end.line, reply.range.end.character); + }, + async provideRenameEdits(document, position, newName) { + if (!client || !client.isRunning()) { + throw new Error("VoidLanguageServer is not running"); + } + const reply = await client.sendRequest("textDocument/rename", { + textDocument: { uri: document.uri.toString() }, + position: { line: position.line, character: position.character }, + newName, + }); + const edit = new vscode.WorkspaceEdit(); + for (const [uri, edits] of Object.entries(reply?.changes ?? {})) { + for (const change of edits as RenameChange[]) { + edit.replace(vscode.Uri.parse(uri), + new vscode.Range(change.range.start.line, + change.range.start.character, + change.range.end.line, + change.range.end.character), + change.newText); + } + } + return edit; + }, + })); +} + +function registerDebug(context: vscode.ExtensionContext): void { + context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('vls-replay', { + resolveDebugConfiguration(_folder, configuration) { + if (!configuration.type && !configuration.request) { + return undefined; + } + if (typeof configuration.trace !== 'string' || !path.isAbsolute(configuration.trace)) { + void vscode.window.showErrorMessage('VLS replay requires an absolute trace path.'); + return undefined; + } + return configuration; + }, + })); + context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory('vls-replay', { + createDebugAdapterDescriptor(session) { + const trace: unknown = session.configuration.trace; + if (typeof trace !== 'string' || !path.isAbsolute(trace)) { + throw new Error('VLS replay requires an absolute trace path.'); + } + const adapter = settings().get('dapPath') || 'vls-dap'; + return new vscode.DebugAdapterExecutable(adapter, ['--replay', trace]); + }, + })); +} + +export interface VlsApi { + client(): LanguageClient | undefined; + providerStatus(): Promise; + analysisStatus(): Promise; + replay(trace: string): Promise; + applyRename(input: RenamePlanInput): Promise<{ applied: boolean; reason?: string }>; + output(): vscode.OutputChannel; +} + +export function activate(context: vscode.ExtensionContext): VlsApi { + output = vscode.window.createOutputChannel('VoidLanguageServer', { log: true }); + context.subscriptions.push(output); + context.subscriptions.push(vscode.commands.registerCommand('vls.start', start)); + context.subscriptions.push(vscode.commands.registerCommand('vls.providerStatus', () => + requestStatus('voidLanguageServer/providerStatus'))); + context.subscriptions.push(vscode.commands.registerCommand('vls.analysisStatus', () => + requestStatus('voidLanguageServer/analysisStatus'))); + context.subscriptions.push(vscode.commands.registerCommand('vls.replay', replay)); + context.subscriptions.push(vscode.commands.registerCommand('vls.stop', stop)); + registerDebug(context); + registerRename(context); + return { + client: () => client, + providerStatus: () => requestStatus('voidLanguageServer/providerStatus'), + analysisStatus: () => requestStatus('voidLanguageServer/analysisStatus'), + replay, + applyRename, + output: () => output, + }; +} + +export async function deactivate(): Promise { + await stop(); +} diff --git a/clients/vscode/src/test/run.ts b/clients/vscode/src/test/run.ts new file mode 100644 index 0000000..c7ba2e4 --- /dev/null +++ b/clients/vscode/src/test/run.ts @@ -0,0 +1,185 @@ +import assert from 'assert'; +import * as crypto from 'crypto'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as vscode from 'vscode'; +import { VlsApi } from '../extension'; + +const EXTENSION = 'vls-local.vls-vscode'; + +async function waitFor(label: string, probe: () => T | undefined | false, + timeout = 20000): Promise { + const deadline = Date.now() + timeout; + while (Date.now() < deadline) { + const value = probe(); + if (value) { + return value; + } + await new Promise(resolve => setTimeout(resolve, 50)); + } + throw new Error(`timed out waiting for ${label}`); +} + +async function waitForAsync(label: string, probe: () => Promise, + timeout = 20000): Promise { + const deadline = Date.now() + timeout; + while (Date.now() < deadline) { + try { + const value = await probe(); + if (value) { + return value; + } + } catch { + // The adapter is not ready yet. + } + await new Promise(resolve => setTimeout(resolve, 100)); + } + throw new Error(`timed out waiting for ${label}`); +} + +async function request(session: vscode.DebugSession, command: string, + args?: unknown): Promise { + return await session.customRequest(command, args) as T; +} + +async function readResult(session: vscode.DebugSession): Promise { + const stack = await request<{ stackFrames: Array<{ id: number }> }>(session, 'stackTrace', + { threadId: 1 }); + const frame = stack.stackFrames[0]; + if (!frame) { + return undefined; + } + const scopes = await request<{ scopes: Array<{ variablesReference: number }> }>( + session, 'scopes', { frameId: frame.id }); + const scope = scopes.scopes[0]; + if (!scope) { + return undefined; + } + const variables = await request<{ variables: Array<{ name: string; value: string }> }>( + session, 'variables', { variablesReference: scope.variablesReference }); + return variables.variables.find(variable => variable.name === 'Result')?.value; +} + +export async function run(): Promise { + const server = process.env.VLS_SERVER; + const adapter = process.env.VLS_DAP; + const trace = process.env.VLS_TRACE; + assert(server && adapter && trace, 'VLS_SERVER, VLS_DAP and VLS_TRACE are required'); + const settings = vscode.workspace.getConfiguration('vls'); + await settings.update('serverPath', server, vscode.ConfigurationTarget.Global); + await settings.update('dapPath', adapter, vscode.ConfigurationTarget.Global); + + const extension = vscode.extensions.getExtension(EXTENSION); + assert(extension, 'VLS extension not found'); + const api = await extension.activate() as VlsApi; + + const folder = vscode.workspace.workspaceFolders?.[0]; + assert(folder, 'the test host requires a workspace folder'); + const document = await vscode.workspace.openTextDocument( + path.join(folder.uri.fsPath, 'unit.cpp')); + await vscode.window.showTextDocument(document); + + await vscode.commands.executeCommand('vls.start'); + await waitFor('language client', () => api.client()?.isRunning()); + const provider = await api.providerStatus() as { state?: unknown }; + assert(typeof provider.state === 'string', JSON.stringify(provider)); + const analysis = await api.analysisStatus() as { state?: unknown }; + assert(typeof analysis.state === 'string', JSON.stringify(analysis)); + + await vscode.commands.executeCommand('vls.replay', trace); + const session = await waitFor('debug session', () => vscode.debug.activeDebugSession); + const first = await waitForAsync('replay session', async () => + await request<{ sessionId?: unknown; generation?: unknown; schemaVersion?: unknown; + sourceSha256?: unknown }>(session, 'vls/session')); + assert(typeof first.sessionId === 'string' && typeof first.generation === 'number', + JSON.stringify(first)); + + const firstValue = await waitForAsync('first recorded value', async () => + await readResult(session)); + assert.strictEqual(firstValue, '17'); + + const timeline = await request<{ events: unknown[]; generation: number; sessionId: string }>( + session, 'vls/timeline', { schemaVersion: first.schemaVersion, sessionId: first.sessionId, + generation: first.generation, start: 0, count: 4 }); + assert(Array.isArray(timeline.events) && timeline.events.length > 0, JSON.stringify(timeline)); + + const source = await request<{ content: string }>(session, 'source', { sourceReference: 1 }); + assert.strictEqual(crypto.createHash('sha256').update(source.content).digest('hex'), + first.sourceSha256); + + await request(session, 'continue', { threadId: 1 }); + const secondValue = await waitForAsync('second recorded value', async () => + await readResult(session)); + assert.strictEqual(secondValue, '34'); + + let staleRejected = false; + try { + await request(session, 'vls/timeline', { schemaVersion: first.schemaVersion, + sessionId: first.sessionId, + generation: first.generation, + start: 0, count: 2 }); + } catch { + staleRejected = true; + } + assert(staleRejected, 'a stale generation was accepted'); + + const second = await request<{ sessionId: string; generation: number; + schemaVersion: number }>(session, 'vls/session'); + assert(second.generation > (first.generation as number)); + const page = await request<{ generation: number }>(session, 'vls/timeline', { + schemaVersion: second.schemaVersion, sessionId: second.sessionId, + generation: second.generation, start: 0, count: 2 }); + assert.strictEqual(page.generation, second.generation); + + await vscode.debug.stopDebugging(session); + await vscode.commands.executeCommand('vls.stop'); + await waitFor('client stop', () => !api.client() || !api.client()?.isRunning()); + // Transactional rename application. + const firstPath = path.join(folder.uri.fsPath, "rename-a.cpp"); + const secondPath = path.join(folder.uri.fsPath, "rename-b.cpp"); + fs.writeFileSync(firstPath, "int value = 1;\n"); + fs.writeFileSync(secondPath, "int value = 2;\n"); + const renameFirst = await vscode.workspace.openTextDocument(firstPath); + const renameSecond = await vscode.workspace.openTextDocument(secondPath); + const changes = { + [renameFirst.uri.toString()]: [{ range: { start: { line: 0, character: 4 }, + end: { line: 0, character: 9 } }, newText: "count" }], + [renameSecond.uri.toString()]: [{ range: { start: { line: 0, character: 4 }, + end: { line: 0, character: 9 } }, newText: "count" }], + }; + const applied = await api.applyRename({ changes }); + assert.strictEqual(applied.applied, true, JSON.stringify(applied)); + assert.strictEqual((await vscode.workspace.openTextDocument(firstPath)).getText(), + "int count = 1;\n"); + assert.strictEqual((await vscode.workspace.openTextDocument(secondPath)).getText(), + "int count = 2;\n"); + + const thirdPath = path.join(folder.uri.fsPath, "rename-c.cpp"); + const fourthPath = path.join(folder.uri.fsPath, "rename-d.cpp"); + fs.writeFileSync(thirdPath, "int value = 3;\n"); + fs.writeFileSync(fourthPath, "int value = 4;\n"); + const third = await vscode.workspace.openTextDocument(thirdPath); + const fourth = await vscode.workspace.openTextDocument(fourthPath); + const stale = { + [third.uri.toString()]: [{ range: { start: { line: 0, character: 4 }, + end: { line: 0, character: 9 } }, newText: "count" }], + [fourth.uri.toString()]: [{ range: { start: { line: 0, character: 4 }, + end: { line: 0, character: 9 } }, newText: "count" }], + }; + const versions = { [third.uri.toString()]: third.version, + [fourth.uri.toString()]: fourth.version }; + const editor = await vscode.window.showTextDocument(third); + await editor.edit(builder => builder.insert(new vscode.Position(0, 0), "// changed\n")); + const rejected = await api.applyRename({ changes: stale, versions }); + assert.strictEqual(rejected.applied, false, JSON.stringify(rejected)); + assert.strictEqual((await vscode.workspace.openTextDocument(fourthPath)).getText(), + "int value = 4;\n"); + const invalid = { + [fourth.uri.toString()]: [{ range: { start: { line: 99, character: 0 }, + end: { line: 99, character: 1 } }, newText: "x" }], + }; + assert.strictEqual((await api.applyRename({ changes: invalid })).applied, false); + assert.strictEqual((await vscode.workspace.openTextDocument(fourthPath)).getText(), + "int value = 4;\n"); + console.log('VSCODE_CLIENT_PASS'); +} diff --git a/clients/vscode/tsconfig.json b/clients/vscode/tsconfig.json new file mode 100644 index 0000000..4b29900 --- /dev/null +++ b/clients/vscode/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "node16", + "moduleResolution": "node16", + "lib": [ + "ES2022" + ], + "outDir": "out", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "sourceMap": true + }, + "include": [ + "src" + ] +} diff --git a/cmake/VoidDependency.cmake b/cmake/VoidDependency.cmake index bbbd93d..562a69e 100644 --- a/cmake/VoidDependency.cmake +++ b/cmake/VoidDependency.cmake @@ -5,10 +5,35 @@ function(vls_add_void_dependency) set(VOID_ENABLE_TESTING OFF) set(VOID_ENABLE_BENCHMARKS OFF) set(BUILD_SHARED_LIBS OFF) - set(VOID_ENABLED_MODULES Configuration Data Unicode) - if(BUILD_TESTING) - list(APPEND VOID_ENABLED_MODULES Testing System) + + find_package(SQLite3 QUIET) + + set(VOID_ENABLED_MODULES + Configuration + Core + Crypto + Data + Functional + Text + Time + Unicode + System + Binary + Async + Resilience + IPC + SystemAsync) + + set(_vls_has_sqlite OFF) + if(SQLite3_FOUND) + list(APPEND VOID_ENABLED_MODULES Sqlite) + set(_vls_has_sqlite ON) endif() + + if(BUILD_TESTING) + list(APPEND VOID_ENABLED_MODULES Testing) + endif() + if(VLS_VOID_SOURCE_DIR) get_filename_component(_vls_void_source "${VLS_VOID_SOURCE_DIR}" ABSOLUTE BASE_DIR "${PROJECT_SOURCE_DIR}") @@ -27,5 +52,7 @@ function(vls_add_void_dependency) EXCLUDE_FROM_ALL SYSTEM) endif() FetchContent_MakeAvailable(voidlibrary) + set(VLS_VOID_TESTING_SCRIPT "${voidlibrary_SOURCE_DIR}/cmake/VoidTesting.cmake" PARENT_SCOPE) + set(VLS_HAS_VOID_SQLITE "${_vls_has_sqlite}" PARENT_SCOPE) endfunction() diff --git a/compiler-patches/gcc-16.2.0/0001-evaluator-events.patch b/compiler-patches/gcc-16.2.0/0001-evaluator-events.patch new file mode 100644 index 0000000..bb2057a --- /dev/null +++ b/compiler-patches/gcc-16.2.0/0001-evaluator-events.patch @@ -0,0 +1,581 @@ +--- a/gcc/c-family/c.opt ++++ b/gcc/c-family/c.opt +@@ -2501,6 +2501,12 @@ + C++ ObjC++ Var(flag_visibility_ms_compat) + Changes visibility to match Microsoft Visual Studio by default. + ++fvls-observe ++C++ Var(flag_vls_observe) Undocumented ++ ++fvls-step ++C++ Var(flag_vls_step) Undocumented ++ + fvtable-gc + C++ ObjC++ WarnRemoved + No longer supported. +--- a/gcc/cp/Make-lang.in ++++ b/gcc/cp/Make-lang.in +@@ -110,7 +110,7 @@ + cp/reflect.o cp/rtti.o \ + cp/search.o cp/semantics.o \ + cp/tree.o cp/typeck.o cp/typeck2.o \ +- cp/vtable-class-hierarchy.o $(CXX_C_OBJS) ++ cp/vls-eval.o cp/vtable-class-hierarchy.o $(CXX_C_OBJS) + + ifeq ($(if $(wildcard ../stage_current),$(shell cat \ + ../stage_current)),stageautofeedback) +--- a/gcc/cp/constexpr.cc ++++ b/gcc/cp/constexpr.cc +@@ -42,6 +42,7 @@ + #include "intl.h" + #include "toplev.h" + #include "contracts.h" ++#include "vls-eval.h" + + static bool verify_constant (tree, bool, bool *, bool *); + #define VERIFY_CONSTANT(X) \ +@@ -4277,6 +4278,10 @@ + return t; + } + ++ vls_eval::call observed; ++ if (flag_vls_observe && get_function_named_in_call (t) == orig_fun) ++ observed.enter (fun); ++ + /* We can't defer instantiating the function any longer. */ + if (!DECL_INITIAL (fun) + && (DECL_TEMPLOID_INSTANTIATION (fun) || DECL_DEFAULTED_FN (fun)) +@@ -4350,7 +4355,11 @@ + new_obj = cxx_fold_indirect_ref (ctx, loc, DECL_CONTEXT (fun), new_obj, + &empty_base, jump_target); + if (*jump_target) +- return NULL_TREE; ++ { ++ if (observed.active ()) ++ observed.outcome (throws (jump_target) ? "throw" : "jump"); ++ return NULL_TREE; ++ } + /* If we're initializing an empty class, don't set constness, because + cxx_fold_indirect_ref will return the wrong object to set constness + of. */ +@@ -4439,7 +4448,10 @@ + { + bool cacheable = !!entry; + if (result && result != error_mark_node) +- /* OK */; ++ { ++ if (observed.active ()) ++ observed.cached (); ++ } + else if (!DECL_SAVED_TREE (fun)) + { + /* When at_eof >= 3, cgraph has started throwing away +@@ -4522,12 +4534,18 @@ + jump_target); + ggc_free (activate); + if (*jump_target) +- return NULL_TREE; ++ { ++ if (observed.active ()) ++ observed.outcome (throws (jump_target) ? "throw" : "jump"); ++ return NULL_TREE; ++ } + } + + ctx->global->metafns_called = false; + + tree jmp_target = NULL_TREE; ++ if (observed.active ()) ++ observed.body (); + cxx_eval_constant_expression (&call_ctx, body, + vc_discard, non_constant_p, overflow_p, + &jmp_target); +@@ -4550,6 +4568,9 @@ + else + { + result = ctx->global->get_value (res); ++ if (observed.active () && result && !*non_constant_p ++ && !*overflow_p && !*jump_target) ++ observed.value (result); + if (result == NULL_TREE && !*non_constant_p + && !DECL_DESTRUCTOR_P (fun)) + { +@@ -4686,6 +4707,21 @@ + clear_no_implicit_zero (result); + + pop_cx_call_context (); ++ if (observed.active ()) ++ { ++ if (*jump_target) ++ observed.outcome (throws (jump_target) ? "throw" : "jump"); ++ else if (*overflow_p) ++ observed.outcome ("overflow"); ++ else if (*non_constant_p || result == error_mark_node) ++ observed.outcome ("failed"); ++ else if (DECL_CONSTRUCTOR_P (fun)) ++ observed.outcome ("constructor"); ++ else if (result == void_node) ++ observed.outcome ("void"); ++ else ++ observed.outcome ("returned"); ++ } + return result; + } + +--- a/gcc/cp/lex.cc ++++ b/gcc/cp/lex.cc +@@ -32,6 +32,7 @@ + #include "gcc-rich-location.h" + #include "cp-name-hint.h" + #include "langhooks.h" ++#include "vls-eval.h" + + static int interface_strcmp (const char *); + static void init_cp_traits (void); +@@ -80,6 +81,8 @@ + cxx_finish (void) + { + c_common_finish (); ++ if (flag_vls_observe) ++ vls_eval::finish (); + } + + ovl_op_info_t ovl_op_info[2][OVL_OP_MAX] = +@@ -350,6 +353,9 @@ + EXPR_STMT, OMP_DEPOBJ + }; + ++ if ((flag_vls_observe || flag_vls_step) && !vls_eval::start ()) ++ return false; ++ + memset (&statement_code_p, 0, sizeof (statement_code_p)); + for (i = 0; i < ARRAY_SIZE (stmt_codes); i++) + statement_code_p[stmt_codes[i]] = true; +--- /dev/null ++++ b/gcc/cp/vls-eval.cc +@@ -0,0 +1,390 @@ ++/* Bounded, opt-in evaluator observation for the private Linux cc1plus. */ ++#include "config.h" ++#include "system.h" ++#include "coretypes.h" ++#include "cp-tree.h" ++#include "vls-eval.h" ++#include ++#include ++ ++namespace vls_eval { ++namespace { ++ ++constexpr int control_fd = 3; ++constexpr int event_fd = 4; ++constexpr unsigned max_events = 4096; ++constexpr size_t max_trace = 1024 * 1024; ++constexpr size_t max_control = 4096; ++constexpr size_t terminal_reserve = 256; ++char nonce[33]; ++unsigned sequence; ++size_t trace_bytes; ++unsigned top; ++bool observing; ++bool stepping; ++ ++// Each event fits in one Linux PIPE_BUF. There are no unbounded fields. ++class record ++{ ++public: ++ char bytes[4096]; ++ size_t size = 0; ++ bool fits = true; ++ ++ explicit record (const char *kind) ++ { ++ append ("{\"v\":1,\"nonce\":\"%s\",\"seq\":%u,\"kind\":\"%s\"", ++ nonce, sequence, kind); ++ } ++ ++ void append (const char *format, ...) ATTRIBUTE_PRINTF_2 ++ { ++ if (!fits) ++ return; ++ va_list ap; ++ va_start (ap, format); ++ int n = vsnprintf (bytes + size, sizeof bytes - size, format, ap); ++ va_end (ap); ++ if (n < 0 || (size_t) n >= sizeof bytes - size) ++ fits = false; ++ else ++ size += n; ++ } ++ ++ // v1 metadata accepts printable ASCII only. Unrepresentable names/paths ++ // are JSON null; quote and backslash are escaped. No source string is a ++ // format string, and all scanning is bounded before any formatting. ++ void text (const char *s) ++ { ++ size_t n = s ? strnlen (s, 513) : 0; ++ if (!s || n > 512) ++ return append ("null"); ++ for (size_t i = 0; i < n; ++i) ++ if ((unsigned char) s[i] < 32 || (unsigned char) s[i] > 126) ++ return append ("null"); ++ append ("\""); ++ for (size_t i = 0; i < n; ++i) ++ { ++ if (s[i] == '"' || s[i] == '\\') ++ append ("\\"); ++ append ("%c", s[i]); ++ } ++ append ("\""); ++ } ++ ++ void frame (unsigned id, unsigned parent) ++ { ++ append (",\"frame\":%u,\"parent\":", id); ++ if (parent) ++ append ("%u", parent); ++ else ++ append ("null"); ++ } ++}; ++ ++long long ++millis () ++{ ++ struct timespec t; ++ if (clock_gettime (CLOCK_MONOTONIC, &t) != 0) ++ _exit (126); ++ return (long long) t.tv_sec * 1000 + t.tv_nsec / 1000000; ++} ++ ++// Recompute the remaining interval across interrupts and partial frames. ++bool ++ready (int fd, short events, long long deadline) ++{ ++ struct pollfd p = {fd, events, 0}; ++ for (;;) ++ { ++ long long left = deadline - millis (); ++ if (left <= 0) ++ return false; ++ int n = poll (&p, 1, (int) left); ++ if (n > 0) ++ return (p.revents & (events | POLLHUP | POLLERR)) != 0; ++ if (n == 0 || errno != EINTR) ++ return false; ++ } ++} ++ ++void ++send_record (const record &r) ++{ ++ size_t done = 0; ++ long long deadline = millis () + 5000; ++ while (done < r.size) ++ { ++ ssize_t n = write (event_fd, r.bytes + done, r.size - done); ++ if (n > 0) ++ done += n; ++ else if (n == 0 || (errno != EINTR && errno != EAGAIN) ++ || !ready (event_fd, POLLOUT, deadline)) ++ _exit (126); // The reader retains only its verified complete prefix. ++ } ++ trace_bytes += r.size; ++ ++sequence; ++} ++ ++void ATTRIBUTE_NORETURN ++terminate_probe (const char *reason, unsigned stop = 0) ++{ ++ record r ("terminal"); ++ r.append (",\"reason\":\"%s\"", reason); ++ if (stop) ++ r.append (",\"stop\":%u", stop); ++ r.append ("}\n"); ++ gcc_assert (r.fits && r.size <= terminal_reserve); ++ send_record (r); ++ _exit (strcmp (reason, "cancelled") == 0 ? 125 : 126); ++} ++ ++unsigned ++publish (record &r) ++{ ++ r.append ("}\n"); ++ if (!r.fits || sequence >= max_events - 1 ++ || trace_bytes + r.size > max_trace - terminal_reserve) ++ terminate_probe ("truncated"); ++ unsigned issued = sequence; ++ send_record (r); ++ return issued; ++} ++ ++bool ++same_pipe (const struct stat &a, const struct stat &b) ++{ ++ return a.st_dev == b.st_dev && a.st_ino == b.st_ino; ++} ++ ++bool ++pipe_mode (int fd, int mode, struct stat &st) ++{ ++ int flags = fcntl (fd, F_GETFL); ++ return fstat (fd, &st) == 0 && S_ISFIFO (st.st_mode) ++ && flags >= 0 && (flags & O_ACCMODE) == mode; ++} ++ ++bool ++set_nonblocking (int fd) ++{ ++ int flags = fcntl (fd, F_GETFL); ++ return flags >= 0 && fcntl (fd, F_SETFL, flags | O_NONBLOCK) == 0; ++} ++ ++bool ++valid_pipes () ++{ ++ struct stat control, events; ++ if (!pipe_mode (control_fd, O_RDONLY, control) ++ || !pipe_mode (event_fd, O_WRONLY, events) || same_pipe (control, events)) ++ return false; ++ for (int fd = 0; fd <= 2; ++fd) ++ { ++ struct stat io; ++ if (fstat (fd, &io) == 0 ++ && (same_pipe (io, events) || same_pipe (io, control))) ++ return false; ++ } ++ return set_nonblocking (control_fd) && set_nonblocking (event_fd); ++} ++ ++bool ++valid_nonce (const char *s) ++{ ++ if (!s || strnlen (s, sizeof nonce) != sizeof nonce - 1) ++ return false; ++ for (size_t i = 0; i < sizeof nonce - 1; ++i) ++ if (!(s[i] >= '0' && s[i] <= '9') && !(s[i] >= 'a' && s[i] <= 'f')) ++ return false; ++ return true; ++} ++ ++void ++await_control (unsigned id, unsigned parent) ++{ ++ record paused ("stopped"); ++ paused.frame (id, parent); ++ unsigned stop = publish (paused); ++ char prefix[64]; ++ size_t prefix_size = snprintf (prefix, sizeof prefix, "%s %u ", nonce, stop); ++ char line[max_control]; ++ size_t used = 0; ++ size_t consumed = 0; ++ long long deadline = millis () + 60000; ++ for (;;) ++ { ++ if (!ready (control_fd, POLLIN, deadline)) ++ terminate_probe ("controlTimeout", stop); ++ char c; ++ ssize_t n = read (control_fd, &c, 1); ++ if (n == 0) ++ terminate_probe ("controlEOF", stop); ++ if (n < 0) ++ { ++ if (errno == EINTR || errno == EAGAIN) ++ continue; ++ terminate_probe ("controlError", stop); ++ } ++ if (++consumed > 4 * max_control || used == sizeof line) ++ terminate_probe ("controlLimit", stop); ++ line[used++] = c; ++ if (c != '\n') ++ continue; ++ const size_t length = used; ++ used = 0; ++ if (length <= prefix_size || memcmp (line, prefix, prefix_size) != 0) ++ continue; ++ const char *action = nullptr; ++ const char *command = line + prefix_size; ++ size_t size = length - prefix_size; ++ if (size == 5 && memcmp (command, "step\n", 5) == 0) ++ action = "step"; ++ else if (size == 9 && memcmp (command, "continue\n", 9) == 0) ++ { ++ stepping = false; ++ action = "continue"; ++ } ++ else if (size == 7 && memcmp (command, "cancel\n", 7) == 0) ++ terminate_probe ("cancelled", stop); ++ else ++ continue; ++ record resumed ("resumed"); ++ resumed.frame (id, parent); ++ resumed.append (",\"stop\":%u,\"action\":\"%s\"", stop, action); ++ publish (resumed); ++ return; ++ } ++} ++ ++} // anonymous namespace ++ ++bool ++start () ++{ ++ const char *s = getenv ("VLS_GCC_NONCE"); ++ if (!flag_vls_observe || !valid_nonce (s) || !valid_pipes () ++ || signal (SIGPIPE, SIG_IGN) == SIG_ERR) ++ { ++ error ("invalid private evaluator observer setup"); ++ return false; ++ } ++ memcpy (nonce, s, sizeof nonce); ++ observing = true; ++ stepping = flag_vls_step; ++ record r ("hello"); ++ r.append (",\"backend\":\"gcc-16.2.0/vls-eval-1\",\"pid\":%ld," ++ "\"capabilities\":[\"integralReturn\",\"cooperativeStep\"]," ++ "\"kinds\":[\"hello\",\"enter\",\"body\",\"value\",\"cached\"," ++ "\"stopped\",\"resumed\",\"leave\",\"terminal\",\"frontendEnd\"]", ++ (long) getpid ()); ++ publish (r); ++ return true; ++} ++ ++void ++finish () ++{ ++ if (observing) ++ { ++ record r ("frontendEnd"); ++ publish (r); ++ observing = false; ++ } ++} ++ ++void ++call::enter (tree decl) ++{ ++ if (!observing || DECL_ARTIFICIAL (decl) || !DECL_NAME (decl)) ++ return; ++ location_t loc = DECL_SOURCE_LOCATION (decl); ++ if (RESERVED_LOCATION_P (loc) || in_system_header_at (loc)) ++ return; ++ m_parent = top; ++ top = m_frame = sequence; // hello consumed zero; each enter is unique. ++ record r ("enter"); ++ r.frame (m_frame, m_parent); ++ r.append (",\"name\":"); ++ r.text (IDENTIFIER_POINTER (DECL_NAME (decl))); ++ // GCC logical declaration location; consumers must map it to a snapshot ++ // before using it as an edit or a physical source identity. ++ expanded_location x = expand_location (loc); ++ if (!from_macro_expansion_at (loc) && x.file && x.line > 0 && x.column > 0) ++ { ++ r.append (",\"sourceKind\":\"logicalDeclaration\",\"source\":"); ++ r.text (x.file); ++ r.append (",\"line\":%d,\"byteColumn\":%d", x.line, x.column); ++ } ++ else ++ r.append (",\"sourceKind\":\"unavailable\""); ++ publish (r); ++} ++ ++void ++call::body () const ++{ ++ record r ("body"); ++ r.frame (m_frame, m_parent); ++ publish (r); ++} ++ ++void ++call::cached () const ++{ ++ record r ("cached"); ++ r.frame (m_frame, m_parent); ++ publish (r); ++} ++ ++void ++call::value (tree result) const ++{ ++ record r ("value"); ++ r.frame (m_frame, m_parent); ++ tree type = TREE_TYPE (result); ++ if (TREE_CODE (result) != INTEGER_CST || !type || !INTEGRAL_TYPE_P (type) ++ || TREE_OVERFLOW (result) || TYPE_PRECISION (type) == 0 ++ || TYPE_PRECISION (type) > 64) ++ { ++ r.append (",\"value\":{\"kind\":\"unavailable\"," ++ "\"reason\":\"unsupportedScalar\"}"); ++ publish (r); ++ return; ++ } ++ ++ unsigned precision = TYPE_PRECISION (type); ++ unsigned HOST_WIDE_INT bits = TREE_INT_CST_LOW (result); ++ // The low limb is sign-extended for narrow signed types. Copy exactly the ++ // type width, including partial high nibbles and the full 64-bit case. ++ if (precision < HOST_BITS_PER_WIDE_INT) ++ bits &= (HOST_WIDE_INT_1U << precision) - 1; ++ unsigned digits = (precision + 3) / 4; ++ char hex[17]; ++ hex[digits] = 0; ++ for (unsigned i = digits; i; --i) ++ { ++ hex[i - 1] = "0123456789abcdef"[bits & 15]; ++ bits >>= 4; ++ } ++ r.append (",\"value\":{\"kind\":\"integer\",\"precision\":%u," ++ "\"signed\":%s,\"bitsHex\":\"%s\"}", precision, ++ TYPE_UNSIGNED (type) ? "false" : "true", hex); ++ publish (r); ++ if (stepping) ++ await_control (m_frame, m_parent); ++} ++ ++void ++call::leave () ++{ ++ gcc_assert (top == m_frame); ++ top = m_parent; ++ record r ("leave"); ++ r.frame (m_frame, m_parent); ++ r.append (",\"outcome\":\"%s\"", m_outcome); ++ publish (r); ++} ++ ++} // namespace vls_eval +--- /dev/null ++++ b/gcc/cp/vls-eval.h +@@ -0,0 +1,32 @@ ++/* Private live constexpr observer for GCC 16.2.0. */ ++#ifndef GCC_CP_VLS_EVAL_H ++#define GCC_CP_VLS_EVAL_H ++ ++namespace vls_eval { ++ ++bool start (); ++void finish (); ++ ++// A dynamic attempt in this invocation. Only numeric IDs and static outcome ++// tags survive a hook. GCC owns all trees, including the result declaration. ++class call ++{ ++ unsigned m_frame = 0; ++ unsigned m_parent; ++ const char *m_outcome = "failed"; ++ void leave (); ++public: ++ call () = default; ++ call (const call &) = delete; ++ call &operator= (const call &) = delete; ++ ~call () { if (active ()) leave (); } ++ bool active () const { return m_frame != 0; } ++ void enter (tree); ++ void body () const; ++ void cached () const; ++ void value (tree) const; ++ void outcome (const char *tag) { m_outcome = tag; } ++}; ++ ++} // namespace vls_eval ++#endif diff --git a/compiler-patches/gcc-16.2.0/0002-ide-occurrences.patch b/compiler-patches/gcc-16.2.0/0002-ide-occurrences.patch new file mode 100644 index 0000000..34025dd --- /dev/null +++ b/compiler-patches/gcc-16.2.0/0002-ide-occurrences.patch @@ -0,0 +1,521 @@ +--- a/gcc/c-family/c.opt ++++ b/gcc/c-family/c.opt +@@ -2501,6 +2501,9 @@ + C++ ObjC++ Var(flag_visibility_ms_compat) + Changes visibility to match Microsoft Visual Studio by default. + ++fvls-ide ++C++ Var(flag_vls_ide) Undocumented ++ + fvls-observe + C++ Var(flag_vls_observe) Undocumented + +--- a/gcc/cp/cp-tree.h ++++ b/gcc/cp/cp-tree.h +@@ -7059,6 +7059,8 @@ + /* Whether we parsed an ellipsis (`...') just before the declarator, + to indicate this is a parameter pack. */ + BOOL_BITFIELD parameter_pack_p : 1; ++ /* The private observer saw a plain identifier token at this cdk_id. */ ++ BOOL_BITFIELD vls_name_token_p : 1; + /* If this declarator is parenthesized, this the open-paren. It is + UNKNOWN_LOCATION when not parenthesized. */ + location_t parenthesized; +--- a/gcc/cp/lex.cc ++++ b/gcc/cp/lex.cc +@@ -353,7 +353,8 @@ + EXPR_STMT, OMP_DEPOBJ + }; + +- if ((flag_vls_observe || flag_vls_step) && !vls_eval::start ()) ++ if ((flag_vls_observe || flag_vls_step || flag_vls_ide) ++ && !vls_eval::start ()) + return false; + + memset (&statement_code_p, 0, sizeof (statement_code_p)); +--- a/gcc/cp/parser.cc ++++ b/gcc/cp/parser.cc +@@ -24,6 +24,7 @@ + #include "system.h" + #include "coretypes.h" + #include "cp-tree.h" ++#include "vls-eval.h" + #include "c-family/c-common.h" + #include "timevar.h" + #include "stringpool.h" +@@ -51,6 +52,35 @@ + #include "builtins.h" + #include "contracts.h" + #include "analyzer/analyzer-language.h" ++ ++/* A commit of the topmost context does not commit its parents. A token ++ in a discarded outer parse must never enter the IDE candidate table. */ ++static bool ++vls_committed (const cp_parser *parser) ++{ ++ for (const cp_parser_context *c = parser->context; c && c->next; c = c->next) ++ if (c->status != CP_PARSER_STATUS_KIND_COMMITTED) ++ { ++ vls_eval::ide::tentative (); ++ return false; ++ } ++ return !processing_template_decl; ++} ++ ++/* Use the actual lexical declarator from this parse, even if GCC merged ++ DECL into an older declaration with a different source location. */ ++static void ++vls_witness_declarator (const cp_parser *parser, tree decl, ++ const cp_declarator *id, bool definition) ++{ ++ if (!decl || (TREE_CODE (decl) != FUNCTION_DECL && TREE_CODE (decl) != FIELD_DECL)) ++ return; ++ while (id && id->kind != cdk_id) ++ id = id->declarator; ++ if (id && id->vls_name_token_p && id->u.id.unqualified_name == DECL_NAME (decl) ++ && vls_committed (parser)) ++ vls_eval::ide::witness (decl, id->id_loc, definition); ++} + + + /* The lexer. */ +@@ -1901,6 +1931,7 @@ + declarator->std_attributes = NULL_TREE; + declarator->declarator = NULL; + declarator->parameter_pack_p = false; ++ declarator->vls_name_token_p = false; + declarator->id_loc = UNKNOWN_LOCATION; + declarator->init_loc = UNKNOWN_LOCATION; + +@@ -8954,6 +8985,25 @@ + + tree stripped_expression + = tree_strip_any_location_wrapper (postfix_expression); ++ /* Keep the terminal identifier while the callee still has its ++ lexical range. The completed call has its caret at '('. */ ++ tree vls_name = NULL_TREE; ++ location_t vls_token = UNKNOWN_LOCATION; ++ if (flag_vls_ide ++ && (TREE_CODE (stripped_expression) == FUNCTION_DECL ++ || TREE_CODE (stripped_expression) == OVERLOAD ++ || identifier_p (stripped_expression))) ++ { ++ cp_token *last = cp_lexer_safe_previous_token (parser->lexer); ++ if (last && last->type == CPP_NAME && !last->tree_check_p ++ && get_pure_location (last->location) ++ == get_pure_location (postfix_expression.get_location ()) ++ && get_finish (last->location) == postfix_expression.get_finish ()) ++ { ++ vls_name = last->u.value; ++ vls_token = last->location; ++ } ++ } + is_builtin_constant_p + = DECL_IS_BUILTIN_CONSTANT_P (stripped_expression); + if (is_builtin_constant_p) +@@ -9130,6 +9180,11 @@ + disallow_virtual, + koenig_p, + complain); ++ if (vls_name && TREE_CODE (postfix_expression) == CALL_EXPR ++ && vls_committed (parser)) ++ vls_eval::ide::occurrence ++ (cp_get_callee_fndecl_nofold (postfix_expression), ++ TREE_TYPE (postfix_expression), vls_name, vls_token); + } + + if (close_paren_loc != UNKNOWN_LOCATION) +@@ -9528,6 +9583,8 @@ + bool dependent_p; + bool pseudo_destructor_p; + tree scope = NULL_TREE; ++ tree vls_name = NULL_TREE; ++ location_t vls_token = UNKNOWN_LOCATION; + location_t start_loc = postfix_expression.get_start (); + + /* If this is a `->' operator, dereference the pointer. */ +@@ -9660,6 +9717,18 @@ + &template_p, + /*declarator_p=*/false, + /*optional_p=*/false)); ++ ++ /* The first token may be a qualifier with the same spelling as the ++ field (b.x::x). Only the terminal name belongs to the field use. */ ++ if (flag_vls_ide && !splice_p && !template_keyword_p) ++ { ++ cp_token *last = cp_lexer_safe_previous_token (parser->lexer); ++ if (last && last->type == CPP_NAME && !last->tree_check_p) ++ { ++ vls_name = last->u.value; ++ vls_token = last->location; ++ } ++ } + + /* In general, build a SCOPE_REF if the member name is qualified. + However, if the name was not dependent and has already been +@@ -9746,6 +9815,11 @@ + && (cp_parser_non_integral_constant_expression + (parser, token_type == CPP_DEREF ? NIC_ARROW : NIC_POINT))) + postfix_expression = error_mark_node; ++ ++ if (vls_name && TREE_CODE (postfix_expression) == COMPONENT_REF ++ && vls_committed (parser)) ++ vls_eval::ide::occurrence (TREE_OPERAND (postfix_expression, 1), ++ TREE_TYPE (postfix_expression), vls_name, vls_token); + + return postfix_expression; + } +@@ -26283,6 +26357,8 @@ + && declarator->id_loc != UNKNOWN_LOCATION + && DECL_SOURCE_LOCATION (decl) == input_location) + DECL_SOURCE_LOCATION (decl) = declarator->id_loc; ++ if (flag_vls_ide && decl && TREE_CODE (decl) == FUNCTION_DECL) ++ vls_witness_declarator (parser, decl, declarator, false); + } + + /* Perform deferred access control checks, now that we know in which +@@ -27156,6 +27232,11 @@ + declarator = make_id_declarator (qualifying_scope, + unqualified_name, + sfk, token->location); ++ if (flag_vls_ide && token == declarator_id_start_token ++ && token->type == CPP_NAME && !token->tree_check_p ++ && !qualifying_scope && sfk == sfk_none ++ && token->u.value == unqualified_name) ++ declarator->vls_name_token_p = true; + declarator->std_attributes = attrs; + declarator->parameter_pack_p = pack_expansion_p; + +@@ -31583,6 +31664,8 @@ + decl = grokfield (declarator, &decl_specifiers, + initializer, /*init_const_expr_p=*/true, + asm_specification, attributes); ++ if (flag_vls_ide && decl && TREE_CODE (decl) == FIELD_DECL) ++ vls_witness_declarator (parser, decl, declarator, true); + + if (parser->fully_implicit_function_template_p) + { +@@ -36071,6 +36154,8 @@ + ? TV_PARSE_INLINE : TV_PARSE_FUNC); + fn = cp_parser_function_definition_after_declarator (parser, + /*inline_p=*/false); ++ if (flag_vls_ide && !seen_error ()) ++ vls_witness_declarator (parser, fn, declarator, true); + } + + return fn; +--- a/gcc/cp/vls-eval.cc ++++ b/gcc/cp/vls-eval.cc +@@ -260,10 +260,19 @@ + + } // anonymous namespace + ++// Shares the bounded v1 writer, but has a distinct handshake and vocabulary. ++#include "vls-ide.inc" ++ + bool + start () + { + const char *s = getenv ("VLS_GCC_NONCE"); ++ if (flag_vls_ide && (!flag_vls_observe || flag_vls_step ++ || !ide::snapshot_setup ())) ++ { ++ error ("invalid private IDE observer setup"); ++ return false; ++ } + if (!flag_vls_observe || !valid_nonce (s) || !valid_pipes () + || signal (SIGPIPE, SIG_IGN) == SIG_ERR) + { +@@ -274,6 +283,12 @@ + observing = true; + stepping = flag_vls_step; + record r ("hello"); ++ if (flag_vls_ide) ++ { ++ ide::hello (r); ++ publish (r); ++ return true; ++ } + r.append (",\"backend\":\"gcc-16.2.0/vls-eval-1\",\"pid\":%ld," + "\"capabilities\":[\"integralReturn\",\"cooperativeStep\"]," + "\"kinds\":[\"hello\",\"enter\",\"body\",\"value\",\"cached\"," +@@ -288,6 +303,8 @@ + { + if (observing) + { ++ if (flag_vls_ide) ++ ide::finish (); + record r ("frontendEnd"); + publish (r); + observing = false; +@@ -297,7 +314,7 @@ + void + call::enter (tree decl) + { +- if (!observing || DECL_ARTIFICIAL (decl) || !DECL_NAME (decl)) ++ if (!observing || flag_vls_ide || DECL_ARTIFICIAL (decl) || !DECL_NAME (decl)) + return; + location_t loc = DECL_SOURCE_LOCATION (decl); + if (RESERVED_LOCATION_P (loc) || in_system_header_at (loc)) +--- a/gcc/cp/vls-eval.h ++++ b/gcc/cp/vls-eval.h +@@ -6,6 +6,12 @@ + + bool start (); + void finish (); ++ ++namespace ide { ++void tentative (); ++void witness (tree, location_t, bool); ++void occurrence (tree, tree, tree, location_t); ++} + + // A dynamic attempt in this invocation. Only numeric IDs and static outcome + // tags survive a hook. GCC owns all trees, including the result declaration. +--- /dev/null ++++ b/gcc/cp/vls-ide.inc +@@ -0,0 +1,244 @@ ++/* Private, read-only GCC 16.2 primary-file occurrence probe. Included in ++ vls-eval.cc to share its bounded record writer and invocation nonce. */ ++namespace ide { ++namespace { ++ ++constexpr unsigned capacity = 256; ++constexpr unsigned max_name = 64; ++char snapshot[65]; ++bool at_capacity, withheld_tentative, withheld_origin, withheld_semantics; ++bool withheld_conflict; ++ ++/* One-based physical byte columns; end is exclusive. No line map, tree, ++ parser, or spelling pointer escapes a parser hook. */ ++struct span ++{ ++ unsigned line, start, end; ++ bool same (const span &s) const ++ { return line == s.line && start == s.start && end == s.end; } ++ void write (record &r) const ++ { ++ r.append ("{\"line\":%u,\"startByte\":%u,\"endByte\":%u}", line, start, end); ++ } ++}; ++ ++struct witness_entry ++{ ++ unsigned uid; ++ span where; ++ bool definition; ++ bool conflict; ++}; ++struct use_entry ++{ ++ unsigned uid; ++ span where; ++ char name[max_name + 1]; ++ bool field; ++ bool is_double; ++ bool conflict; ++}; ++witness_entry targets[capacity]; ++use_entry uses[capacity]; ++unsigned target_count, use_count; ++ ++bool ++plain_name (tree decl) ++{ ++ if (!decl || (TREE_CODE (decl) != FUNCTION_DECL && TREE_CODE (decl) != FIELD_DECL) ++ || DECL_ARTIFICIAL (decl) || !DECL_NAME (decl)) ++ return false; ++ if (TREE_CODE (decl) == FUNCTION_DECL ++ && (!TREE_TYPE (decl) || TREE_CODE (TREE_TYPE (decl)) != FUNCTION_TYPE ++ || (DECL_CONTEXT (decl) && TYPE_P (DECL_CONTEXT (decl))) ++ || (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)))) ++ return false; ++ tree id = DECL_NAME (decl); ++ unsigned length = IDENTIFIER_LENGTH (id); ++ if (!length || length > max_name) ++ return false; ++ const char *name = IDENTIFIER_POINTER (id); ++ for (unsigned i = 0; i != length; ++i) ++ if (!(name[i] >= 'a' && name[i] <= 'z') && !(name[i] >= 'A' && name[i] <= 'Z') ++ && !(i && name[i] >= '0' && name[i] <= '9') && name[i] != '_') ++ return false; ++ return true; ++} ++ ++bool ++primary_token (location_t token, unsigned length, span &out) ++{ ++ location_t start = get_pure_location (get_start (token)); ++ location_t last = get_pure_location (get_finish (token)); ++ if (RESERVED_LOCATION_P (start) || RESERVED_LOCATION_P (last) ++ || get_pure_location (token) != start ++ || from_macro_expansion_at (start) || from_macro_expansion_at (last)) ++ return false; ++ const line_map *m = linemap_lookup (line_table, start); ++ if (!m || !MAP_ORDINARY_P (m) || linemap_lookup (line_table, last) != m) ++ return false; ++ const line_map_ordinary *map = linemap_check_ordinary (m); ++ if (!MAIN_FILE_P (map) || map->sysp || !map->to_file || !main_input_filename ++ || strcmp (map->to_file, main_input_filename) != 0) ++ return false; ++ unsigned line = SOURCE_LINE (map, start); ++ unsigned column = SOURCE_COLUMN (map, start); ++ unsigned final = SOURCE_COLUMN (map, last); ++ if (!line || !column || SOURCE_LINE (map, last) != line || final < column ++ || final == UINT_MAX || final - column + 1 != length) ++ return false; ++ out = {line, column, final + 1}; ++ return true; ++} ++ ++witness_entry * ++find_target (unsigned uid) ++{ ++ for (unsigned i = 0; i < target_count; ++i) ++ if (targets[i].uid == uid) ++ return &targets[i]; ++ return nullptr; ++} ++ ++} // anonymous namespace ++ ++bool ++snapshot_setup () ++{ ++ const char *s = getenv ("VLS_GCC_SNAPSHOT"); ++ if (!s || strnlen (s, sizeof snapshot) != sizeof snapshot - 1) ++ return false; ++ for (unsigned i = 0; i < sizeof snapshot - 1; ++i) ++ if (!(s[i] >= '0' && s[i] <= '9') && !(s[i] >= 'a' && s[i] <= 'f')) ++ return false; ++ memcpy (snapshot, s, sizeof snapshot); ++ return true; ++} ++ ++void ++hello (record &r) ++{ ++ r.append (",\"backend\":\"gcc-16.2.0/vls-ide-1\",\"pid\":%ld," ++ "\"capabilities\":[\"primaryFileOccurrences\"]," ++ "\"kinds\":[\"hello\",\"occurrence\",\"ideCoverage\"," ++ "\"terminal\",\"frontendEnd\"],\"snapshot\":\"%s\"", ++ (long) getpid (), snapshot); ++} ++ ++void ++tentative () ++{ ++ withheld_tentative = true; ++} ++ ++void ++witness (tree decl, location_t token, bool definition) ++{ ++ if (at_capacity || !plain_name (decl)) ++ return; ++ span where; ++ if (!primary_token (token, IDENTIFIER_LENGTH (DECL_NAME (decl)), where)) ++ { ++ withheld_origin = true; ++ return; ++ } ++ unsigned uid = DECL_UID (decl); ++ if (witness_entry *old = find_target (uid)) ++ { ++ if (definition && !old->definition) ++ *old = {uid, where, true, false}; ++ else if (definition && !old->where.same (where)) ++ old->conflict = withheld_conflict = true; ++ return; ++ } ++ if (target_count == capacity) ++ at_capacity = true; ++ else ++ targets[target_count++] = {uid, where, definition, false}; ++} ++ ++void ++occurrence (tree decl, tree type, tree token_name, location_t token) ++{ ++ if (at_capacity) ++ return; ++ if (!plain_name (decl) || DECL_NAME (decl) != token_name ++ || (type != integer_type_node && type != double_type_node)) ++ { ++ withheld_semantics = true; ++ return; ++ } ++ span where; ++ unsigned length = IDENTIFIER_LENGTH (token_name); ++ if (!primary_token (token, length, where)) ++ { ++ withheld_origin = true; ++ return; ++ } ++ unsigned uid = DECL_UID (decl); ++ bool field = TREE_CODE (decl) == FIELD_DECL; ++ bool is_double = type == double_type_node; ++ for (unsigned i = 0; i < use_count; ++i) ++ if (uses[i].where.same (where)) ++ { ++ if (uses[i].uid != uid || uses[i].field != field || uses[i].is_double != is_double) ++ uses[i].conflict = withheld_conflict = true; ++ return; ++ } ++ if (use_count == capacity) ++ { ++ at_capacity = true; ++ return; ++ } ++ use_entry &u = uses[use_count++]; ++ u = {uid, where, {}, field, is_double, false}; ++ memcpy (u.name, IDENTIFIER_POINTER (token_name), length); ++} ++ ++void ++finish () ++{ ++ /* A same-name #line can give two distinct tokens identical logical ++ filename/line/column, even if their bytes are identical. Suppress the ++ entire set before publishing its first member. Includes can also set ++ this flag. The IDE harness supplies one include-free primary snapshot. */ ++ const char *reason = nullptr; ++ if (line_table->seen_line_directive) ++ reason = "lineDirective"; ++ else if (seen_error ()) ++ reason = "compileErrors"; ++ else if (at_capacity) ++ reason = "capacity"; ++ if (!reason) ++ for (unsigned i = 0; i < use_count; ++i) ++ { ++ const use_entry &u = uses[i]; ++ if (u.conflict) ++ continue; ++ const witness_entry *w = find_target (u.uid); ++ const bool known = w && !w->conflict; ++ record r ("occurrence"); ++ r.append (",\"sourceKind\":\"primaryFileToken\",\"role\":\"%s\"," ++ "\"declUid\":%u,\"name\":", u.field ? "field" : "call", u.uid); ++ r.text (u.name); ++ r.append (",\"resultType\":\"%s\",\"use\":", u.is_double ? "double" : "int"); ++ u.where.write (r); ++ const char *kind = known ? (w->definition ? "definition" : "declaration") : "unavailable"; ++ r.append (",\"targetKind\":\"%s\",\"target\":", kind); ++ if (known) ++ w->where.write (r); ++ else ++ r.append ("null"); ++ publish (r); ++ } ++ record coverage ("ideCoverage"); ++ coverage.append (",\"source\":"); ++ coverage.text (main_input_filename); ++ coverage.append (",\"state\":\"%s\",\"reason\":", reason ? "unavailable" : "partial"); ++ coverage.text (reason); ++ coverage.append (",\"tentative\":%s,\"unmapped\":%s,\"unsupported\":%s,\"conflict\":%s", ++ withheld_tentative ? "true" : "false", withheld_origin ? "true" : "false", ++ withheld_semantics ? "true" : "false", withheld_conflict ? "true" : "false"); ++ publish (coverage); ++} ++} // namespace ide diff --git a/compiler-patches/gcc-16.2.0/0003-physical-utf8-origin.patch b/compiler-patches/gcc-16.2.0/0003-physical-utf8-origin.patch new file mode 100644 index 0000000..154a5aa --- /dev/null +++ b/compiler-patches/gcc-16.2.0/0003-physical-utf8-origin.patch @@ -0,0 +1,98 @@ +--- /dev/null ++++ b/libcpp/include/vls-primary-origin.h +@@ -0,0 +1,9 @@ ++/* Source origin for the private VLS GCC frontend. */ ++#ifndef LIBCPP_VLS_PRIMARY_ORIGIN_H ++#define LIBCPP_VLS_PRIMARY_ORIGIN_H ++ ++struct cpp_reader; ++/* Bytes skipped on the first physical line, or -1 for an unverified input. */ ++extern int cpp_vls_primary_utf8_prefix (const cpp_reader *); ++ ++#endif +--- a/libcpp/files.cc ++++ b/libcpp/files.cc +@@ -23,6 +23,7 @@ + #include "config.h" + #include "system.h" + #include "cpplib.h" ++#include "vls-primary-origin.h" + #include "internal.h" + #include "mkdeps.h" + #include "obstack.h" +@@ -102,6 +103,10 @@ + + /* Number of times the file has been stacked for preprocessing. */ + unsigned short stack_count; ++ ++ /* For the VLS observer, 0 means unknown. Otherwise this records one ++ plus the byte prefix consumed on line one of the actual UTF-8 input. */ ++ unsigned char vls_primary_utf8_prefix; + + /* If opened with #import or contains #pragma once. */ + bool once_only : 1; +@@ -796,12 +801,19 @@ + cpp_error_at (pfile, CPP_DL_WARNING, loc, + "%s is shorter than expected", file->path); + ++ const bool record_origin = (pfile && file == pfile->main_file && input_charset ++ && !strcasecmp (input_charset, "UTF-8")); ++ const int prefix = record_origin ? cpp_check_utf8_bom ((const char *) buf, total) : 0; + file->buffer = _cpp_convert_input (pfile, + input_charset, + buf, size + pad, total, + &file->buffer_start, + &file->st.st_size); + file->buffer_valid = file->buffer; ++ if (record_origin && file->buffer_valid ++ && file->buffer - file->buffer_start == prefix ++ && file->st.st_size == (off_t) (total - prefix)) ++ file->vls_primary_utf8_prefix = 1 + prefix; + return file->buffer_valid; + } + +@@ -2360,6 +2372,16 @@ + } + } + ++/* The conversion result is retained after the preprocessor releases its ++ input buffer. Asking for an origin never reopens a mutable pathname. */ ++int ++cpp_vls_primary_utf8_prefix (const cpp_reader *pfile) ++{ ++ if (!pfile || !pfile->main_file) ++ return -1; ++ return (int) pfile->main_file->vls_primary_utf8_prefix - 1; ++} ++ + /* Return the file name associated with FILE. */ + const char * + _cpp_get_file_name (_cpp_file *file) +--- a/gcc/cp/vls-eval.cc ++++ b/gcc/cp/vls-eval.cc +@@ -4,6 +4,8 @@ + #include "coretypes.h" + #include "cp-tree.h" + #include "vls-eval.h" ++#include "c-family/c-pragma.h" ++#include "vls-primary-origin.h" + #include + #include + +--- a/gcc/cp/vls-ide.inc ++++ b/gcc/cp/vls-ide.inc +@@ -87,7 +87,13 @@ + if (!line || !column || SOURCE_LINE (map, last) != line || final < column + || final == UINT_MAX || final - column + 1 != length) + return false; +- out = {line, column, final + 1}; ++ const int skipped = cpp_vls_primary_utf8_prefix (parse_in); ++ if (skipped < 0) ++ return false; ++ const unsigned prefix = line == 1 ? (unsigned) skipped : 0; ++ if (prefix > UINT_MAX - (final + 1)) ++ return false; ++ out = {line, column + prefix, final + 1 + prefix}; + return true; + } + diff --git a/compiler-patches/gcc-16.2.0/0004-splice-origins.patch b/compiler-patches/gcc-16.2.0/0004-splice-origins.patch new file mode 100644 index 0000000..e4e806f --- /dev/null +++ b/compiler-patches/gcc-16.2.0/0004-splice-origins.patch @@ -0,0 +1,103 @@ +--- a/gcc/cp/reflect.cc ++++ b/gcc/cp/reflect.cc +@@ -31,6 +31,7 @@ + #include "c-family/c-pragma.h" // for parse_in + #include "gimplify.h" // for unshare_expr + #include "metafns.h" ++#include "vls-eval.h" + + static tree eval_is_function_type (tree); + static tree eval_is_object_type (location_t, const constexpr_ctx *, tree, +@@ -8770,6 +8771,7 @@ + return error_mark_node; + + refl = REFLECT_EXPR_HANDLE (refl); ++ vls_eval::splice (loc, refl); + /* Function templates are wrapped in OVERLOAD from name lookup + and a lot of places assume that. Furthermore, if reflection comes + from ^^fntmpl, it is wrapped with OVERLOAD already, only when +--- a/gcc/cp/vls-eval.cc ++++ b/gcc/cp/vls-eval.cc +@@ -294,7 +294,8 @@ + r.append (",\"backend\":\"gcc-16.2.0/vls-eval-1\",\"pid\":%ld," + "\"capabilities\":[\"integralReturn\",\"cooperativeStep\"]," + "\"kinds\":[\"hello\",\"enter\",\"body\",\"value\",\"cached\"," +- "\"stopped\",\"resumed\",\"leave\",\"terminal\",\"frontendEnd\"]", ++ "\"stopped\",\"resumed\",\"leave\",\"terminal\",\"frontendEnd\"," ++ "\"splice\"]", + (long) getpid ()); + publish (r); + return true; +@@ -406,4 +407,59 @@ + publish (r); + } + ++// One splice record carries both ends of the first provenance link: the ++// editable splice site and the reflected entity it designates. Identity is ++// composed by the consumer from the target kind, name and location; the ++// compiler never invents a source spelling. ++void ++splice (location_t loc, tree entity) ++{ ++ if (!observing || flag_vls_ide || RESERVED_LOCATION_P (loc) ++ || in_system_header_at (loc) || from_macro_expansion_at (loc)) ++ return; ++ expanded_location x = expand_location (loc); ++ if (!x.file || x.line <= 0 || x.column <= 0) ++ return; ++ record r ("splice"); ++ r.append (",\"source\":"); ++ r.text (x.file); ++ r.append (",\"line\":%d,\"byteColumn\":%d", x.line, x.column); ++ const char *kind = "value"; ++ tree name = NULL_TREE; ++ location_t target_loc = UNKNOWN_LOCATION; ++ if (entity && DECL_P (entity)) ++ { ++ kind = "declaration"; ++ name = DECL_NAME (entity); ++ target_loc = DECL_SOURCE_LOCATION (entity); ++ } ++ else if (entity && TYPE_P (entity)) ++ { ++ kind = "type"; ++ name = TYPE_IDENTIFIER (entity); ++ if (!name && TYPE_NAME (entity) && DECL_P (TYPE_NAME (entity))) ++ { ++ name = DECL_NAME (TYPE_NAME (entity)); ++ target_loc = DECL_SOURCE_LOCATION (TYPE_NAME (entity)); ++ } ++ } ++ r.append (",\"targetKind\":\"%s\",\"targetName\":", kind); ++ r.text (name ? IDENTIFIER_POINTER (name) : nullptr); ++ if (!RESERVED_LOCATION_P (target_loc)) ++ { ++ expanded_location y = expand_location (target_loc); ++ if (y.file && y.line > 0 && y.column > 0) ++ { ++ r.append (",\"targetSource\":"); ++ r.text (y.file); ++ r.append (",\"targetLine\":%d,\"targetByteColumn\":%d", y.line, y.column); ++ publish (r); ++ return; ++ } ++ } ++ r.append (",\"targetSource\":null,\"targetLine\":null," ++ "\"targetByteColumn\":null"); ++ publish (r); ++} ++ + } // namespace vls_eval +--- a/gcc/cp/vls-eval.h ++++ b/gcc/cp/vls-eval.h +@@ -7,6 +7,10 @@ + bool start (); + void finish (); + ++// Records one evaluated splice: the splice site and the entity it names. ++// Only the observe invocation and only non-system, non-macro locations. ++void splice (location_t, tree); ++ + namespace ide { + void tentative (); + void witness (tree, location_t, bool); diff --git a/compiler-patches/gcc-16.2.0/configure.args b/compiler-patches/gcc-16.2.0/configure.args new file mode 100644 index 0000000..a83bae5 --- /dev/null +++ b/compiler-patches/gcc-16.2.0/configure.args @@ -0,0 +1,3 @@ +# GCC 16.2.0 configure options recorded from the verified private build. --disable-fixincludes +# @PREFIX@ is the private install prefix selected by tools/prepare-private-gcc. --disable-fixincludes +--with-native-system-header-dir=/nix/store/2f69qaci676cq5kr8svry3gbf6i6iqzi-glibc-2.44-57-dev/include --prefix=@PREFIX@ --disable-bootstrap --disable-multilib --enable-checking=release --disable-nls --disable-libsanitizer --disable-libgomp --disable-libquadmath --disable-libssp --disable-libvtv --without-isl --with-gmp-include=/nix/store/fs234b3nv0bv3jij5nf6jkpj5n575g8i-gmp-with-cxx-6.3.0-dev/include --with-gmp-lib=/nix/store/x4n20j5hd4y4f6a0lhqikyzypqf4lk7q-gmp-6.3.0/lib --with-mpfr-include=/nix/store/sm1kd9fm3i78kml51vylmnd084gxa274-mpfr-4.2.2-dev/include --with-mpfr-lib=/nix/store/qfhbm2s6dzsx3f296kkbmvjfzrpmlylf-mpfr-4.2.2/lib --with-mpc=/nix/store/bcxjqlilnadv2viv17zk47lz3900dc75-libmpc-1.4.1 --enable-languages=c,c++,lto --disable-fixincludes diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md index 3a04305..f578e6d 100644 --- a/docs/DEPENDENCIES.md +++ b/docs/DEPENDENCIES.md @@ -2,12 +2,15 @@ ## VoidLibrary Source: https://git.faumaray.com/Void/VoidLibrary.git -Inspected baseline: 9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5 (2026-11-25). -This is the tested baseline, not proof of JSON conformance. User decision D-021 -supersedes the original pin policy: CMake follows main. Record the actual fetched -commit for every verification run and rerun configuration to check upstream updates. -The decimal-capable main revision must pass the ingress capability suite before -final shell acceptance; following main does not automatically establish readiness. +Tested main: 7d7d23ec0a6a55d4b30921432fa215b29a29e59b (2026-11-27). +User decision D-021 supersedes the original pin policy: the dependency reference is +main. Record the actual fetched commit for every verification run. Use cmake --fresh +with explicit build settings to refresh CMake's dependency population stamps; ordinary +reconfiguration retained the old9931c5f checkout in the observed build tree. +The new revision implements decimal/exponent parsing and checked serialization. +The six original JSON capability cases pass. T-REVIEW-003 identified loss of +request-ID precision and rejection of syntactically valid numbers outside +machine range. The expanded eight-case suite retains both failing regressions. Use Configuration/Argparse, Data, Unicode, System and Testing through their verified public APIs. Later modules may reuse Async, Time, Functional, Memory, IPC or Sqlite @@ -20,18 +23,28 @@ external checkout. The approved initial work does not include VoidLibrary patche ## Void Build System Local source: /home/faumaray/Projects/VoidBuildSystem. -Planning initially observed an unborn bootstrap. Execution observed -3cac890ce9b8a0681130a58601e0516231471ad8 on main with active changes to build descriptions. +Planning initially observed an unborn bootstrap. The2026-11-27 resumption observed +6c225c2dff58b64fe8dbb0e5072f8e23f566efe5 on main with active tracked changes. This moving checkout is reference evidence, not a pinned runtime dependency. -Its native resolved tooling export remains a NEW cross-project contract; no -VBS source files are owned by this task. +Editor generation, profile selection and IDE query APIs now exist. Their coverage +of the required native tooling contract and live behavior remains to be assessed; +no VBS source files are owned by this task. ## Candidate semantic frontend https://github.com/bloomberg/clang-p2996 Candidate revision: 562409c7942690d59ea470762515f88f24b16e23. -No toolchain is downloaded or linked by milestone0. Its P2996 documentation -explicitly lacks constexpr-range expansion, used in VoidLibrary Enum.hpp. -The candidate must pass GCC16/libstdc++ compatibility and separate debugging gates. +The reference corpus builds and runs the public Void enum helpers and a module +importer with GCC 16.2 and its libstdc++. At the exact candidate revision the +status document still lists a limitation on constexpr ranges, while its libc++ +test suite contains an enum-to-string expansion over reflected enumerators. +Compiler and standard-library compatibility need separate measurements. The +isolated source build lives under `build/frontend-gate`. See the +[candidate status](https://github.com/bloomberg/clang-p2996/blob/562409c7942690d59ea470762515f88f24b16e23/P2996.md) +and [upstream test](https://github.com/bloomberg/clang-p2996/blob/562409c7942690d59ea470762515f88f24b16e23/libcxx/test/std/experimental/reflection/p2996-ex-enum-to-string.pass.cpp). +The built Clang 21.0.0git candidate passed basic modules, splice syntax and the +constexpr-range control. It failed the actual Void enum helpers and the +reflection-bearing module importer with GCC 16.2's libstdc++. Gate 1 rejects +this revision as the sole frontend. Debugging and IDE quality were not established. A source-level debugger API must not be inferred from Clang's compiler debug helpers. See roadmap08 and17. Compiler fixes/replacement require a new explicit decision. diff --git a/docs/agent-workflow/APPROVED_PLAN.md b/docs/agent-workflow/APPROVED_PLAN.md index 74137fc..0a0cdb3 100644 --- a/docs/agent-workflow/APPROVED_PLAN.md +++ b/docs/agent-workflow/APPROVED_PLAN.md @@ -36,3 +36,11 @@ The user subsequently instructed: "not yet implemented, watch main no need to pi VoidLibrary now follows main by default; historical pin instructions above and in T-001 are superseded. Record the exact tested commit and validate upstream JSON changes. The final JSON acceptance gate remains mandatory. + +## November 27 implementation scope + +D-022 through D-027 authorize all 27 plans, prioritize the primary native VBS +build, and select the feat/implement-roadmap branch. The user approved continued +work on the existing document/protocol/workspace files and explicitly selected +GPT-6.2 Astra/Sol at Max for delegated work. The November 25 scope above records +the original bootstrap milestone. diff --git a/docs/agent-workflow/DECISIONS.md b/docs/agent-workflow/DECISIONS.md index 1e66d99..d18150e 100644 --- a/docs/agent-workflow/DECISIONS.md +++ b/docs/agent-workflow/DECISIONS.md @@ -11,7 +11,7 @@ Date: 2026-11-25. These are user choices unless explicitly marked proposed. | D-005 | Neovim and VS Code | CONFIRMED; both are acceptance clients | | D-006 | Core IDE plus modules/reflection | CONFIRMED; diagnostics/completion/hover/navigation/references/safe rename | | D-007 | Metadata refresh and private IDE caches | CONFIRMED; trusted metadata scope, explicit project generator/dependency builds | -| D-008 | CMake now, VBS later | CONFIRMED; native VBS self-build has its own gate | +| D-008 | CMake now, VBS later | HISTORICAL; superseded by D-025 making VBS primary now | | D-009 | VoidLibrary and VBS adoption first | CONFIRMED; remaining Void projects follow evidence | | D-010 | Probe Clang reflection fork first | CONFIRMED; reject unsupported GCC-context fidelity; no implicit compiler repairs | | D-011 | Defer license until backend decision | CONFIRMED; do not add an invented LICENSE | @@ -25,6 +25,15 @@ Date: 2026-11-25. These are user choices unless explicitly marked proposed. | D-019 | Upstream worker will add Void JSON decimals | CONFIRMED user report, implementation NOT yet verified; dependency gate | | D-020 | Implement the plan | CONFIRMED; authorizes milestone0 local writes, no commit/push/deploy | | D-021 | Follow VoidLibrary main; no commit pin | CONFIRMED execution follow-up: "not yet implemented, watch main no need to pin"; supersedes previous VoidLibrary pin requirements, retains exact tested-commit evidence and JSON acceptance gate | +| D-022 | Implement all plans | CONFIRMED2026-11-27; expands beyond bootstrap while retaining the full27-part requirements and gates | +| D-023 | Max effort for all agents/subagents | CONFIRMED and explicitly corrected from XHigh; current configured roles are locked to XHigh, so no new delegation has run | +| D-024 | Continue existing dirty foundation code | CONFIRMED; user reports no active writer; preserve and integrate the current files | +| D-025 | VoidBuildSystem is the primary build system | CONFIRMED; overrides CMake-first sequencing; prioritize native VBS build/test support now | +| D-026 | Work on a separate branch | CONFIRMED; root created feat/implement-roadmap and carried all existing changes without commit/push | +| D-027 | GPT-6.2 family at Max for each delegated assignment | User approved the generic runtime role with explicit model and effort after escalation, then requested the 6.2 family. Use gpt-6.2-astra for planning, review and difficult implementation, and gpt-6.2-sol for general implementation. Preserve independent assignments. | +| D-028 | Evaluate GCC 16 as a backend after the Clang fidelity failure | The user selected the same IDE and debugger gates for GCC. Evaluate the installed frontend and its inspection interfaces. Production backend selection, compiler modifications and project licensing remain separate decisions. | +| D-029 | Keep independent review on GPT-6.2 Astra at Max | The user chose to retry after two HTTP 429 responses. Record the outstanding review and continue independent work. | +| D-030 | Prototype the isolated GCC worker and versioned compiler hooks locally | The user authorized local changes against GCC 16.2 after the overload, recovery and module probes. Distribution and the VLS project license are deferred. | ## Root technical defaults accepted into the reviewed plan - LSP3.17 compatibility, stdio, empty semantic capability set in bootstrap. @@ -44,3 +53,22 @@ provided independent official-source frontend evidence. The later upstream-statu follow-up created no new implementation package while in Plan Mode, so its Sol candidate was not dispatched. The execution-turn Sol candidate owns T-001. Roles are configured XHigh; model execution was not independently verified. + +## D-031: Stock GCC diagnostics are enabled by default + +The user selected default-on stock GCC diagnostics over an explicit opt-in flag +("diagnostics by default"). The server therefore prepares its GCC profile in +process from the workspace-selected GCC driver when no profile is supplied, so +no external Python script is required for normal use. + +Consequences: +- Workspace build metadata can cause the selected GCC compiler to run for + analysis. The command is still the checked, sandboxed invocation; metadata + never supplies plugins, wrappers or arbitrary options. +- The occurrence observer remains optional: without a launcher-selected + observer artifact, diagnostics work and hover/definition stay unavailable. +- An explicitly supplied `--gcc-profile` still takes precedence, and + `--provider none` remains available for passive sessions. + +Implementation status: decided, not yet implemented. `GccProfile::prepare()` in +C++ and the launcher default are the next package. diff --git a/docs/agent-workflow/PREFLIGHT.md b/docs/agent-workflow/PREFLIGHT.md index 07c5552..792994a 100644 --- a/docs/agent-workflow/PREFLIGHT.md +++ b/docs/agent-workflow/PREFLIGHT.md @@ -1,5 +1,85 @@ # Preflight record +## Stock occurrence host contract on December 5 + +Root preflight of the consumer boundary for T-STOCK-OCCURRENCES-014. An +independent reviewer was not available for this pass; these are root +dispositions. The producer artifact and its sealed verifier are already +verified. + +Initial verdict: CHANGES_REQUIRED. Corrected host contract: + +| Finding | Binding correction | +| --- | --- | +| The observer could be swapped after profile load | The launcher-selected profile records an absolute path and SHA-256. Every job re-reads bounded bytes, hashes the exact staged copy and withholds facts on mismatch. Metadata, settings or a compilation database cannot name a plugin. | +| Report paths could escape the compiled inputs | Decoding requires exact logical-path membership in the capture that was compiled. An unknown path rejects the report instead of being dropped. | +| Physical byte columns are not LSP characters | Convert one-based physical byte spans through the captured snapshot's negotiated encoding. Require the sliced bytes to equal the declared name and both endpoints to be UTF-8 boundaries. | +| Facts could outlive their inputs | Occurrences belong to the receipt's capture and analysis revision. Lease or capture invalidation drops them; no cross-generation reuse. | +| Partial reports could fabricate completeness | `complete:false` publishes zero facts. `partial:true` still serves individually verified facts. A missing or unproven definition is `null`, never a guessed link. | +| A capability could be advertised without a producer | `hoverProvider` and `definitionProvider` are advertised only when the selected profile enables the observer. | +| Readable data could become executable | Facts are rendered as text only. No recorded string is executed, opened as a workspace file or used as a path. | + +## Compiler input capture and recorded debugging + +The reviewers cleared three amended contracts. The document store retains +file membership independently of selected text revisions. Source capture +checks the job's actual grant set, its original editor census and incompatible +ancestor/descendant requests. A recording retains the acknowledged stop and +action and the cursor at each compiler event. Four real compiler journals +distinguished completion, cancellation, stepping and resuming through later +values. A later independent review of the module planner and diagnostic +decoder completed after four corrections. The DAP preflight also required +binary captured source to retain its digest and length when a DAP text +response cannot represent it. The integrated DAP reviewer checked the +remaining paging, control, transport and handle ownership contracts. + +## Module planning, diagnostics and compiler context + +Independent GPT-6.2 Astra assignments at Max cleared three amended contracts. +The module graph needs a closed census, a current header-CMI identity and all +lookup roots. The diagnostic mapper needs the actual owning input and evidence +for physical origin and column units. A stock GCC header using `#line` reproduced +the wrong-location case with identical text. The workspace lease must choose +the active row before checking its driver, preserve explicit or implicit root +routing, and expire replaced evidence even when its content digest recurs. +The review exercised a two-driver revocation and identical-byte DB replacement. + +## Provider and private compiler contracts on November 27 + +The GPT-6.2 Astra reviewer cleared all four provider contracts after amendment. +The file reader anchors directory grants and distinguishes a genuinely absent +selector from a dangling link or missing generation. The importer verifies +driver authority before response-file reads and checks the sole source operand +against the row. Native selection rechecks the full profile, selected generation +and ticket. The session rechecks positive inputs and selector absence together +with folder incarnation, settings, trust and latest observation before publishing. + +The GCC preflight cleared capture of real integral returns, the fixed Linux +launcher and bounded supervisor/control/replay. It required explicit provisional +values until evaluator cleanup, an immutable checked executable, one-use +controls bound to each observed stop, the compiler's resume acknowledgement +and final process reaping. The separate IDE contract requires positive +definition evidence, physical use and target ranges, all-level tentative-parse +handling and explicit gaps for ambiguous source maps. The reviewer reproduced +two same-file line-directive mappings with colliding displayed coordinates. +The implementation still needs independent integrated review. + +## Foundation review on November 27 + +T-PREFLIGHT-004 accepted the amended preparation, protocol, documents and +passive trust contracts. The reviewer required changes to the remaining two +contracts before implementation. Root incorporated the following dispositions. + +| Contract | Correction applied | +| --- | --- | +| T-SESSION-003 | Validate coordinates against INT32_MAX before clamping. Distinguish absent and null ranges. A malformed late event in a known document sets its version barrier. Verify edits through a split-scalar error from an actual process in each negotiated encoding. | +| T-MODEL-005 | Bind to the owning TU and stable disk/overlay identity. Track previously unsuccessful include/import lookup evidence or invalidate all lookup roots conservatively. Record operation-specific completeness. Coordinate cancellation, revalidation and installation under one transition. | + +Root verified the provider-facing inputs against the new document/trust headers. +The independent reviewer's continuation and a fresh same-model attempt returned +HTTP 429. The corrections above are root dispositions. A second independent +verdict and a final review of the integrated changes are outstanding. + Date: 2026-11-25. Scope: initial shell/documents and gated future roadmap. Configured independent astra_reviewer (gpt-6-astra/XHigh); runtime model routing was not independently exposed by spawn metadata. diff --git a/docs/agent-workflow/RESUMPTION-2026-11-27.md b/docs/agent-workflow/RESUMPTION-2026-11-27.md new file mode 100644 index 0000000..14cbdcc --- /dev/null +++ b/docs/agent-workflow/RESUMPTION-2026-11-27.md @@ -0,0 +1,90 @@ +# Implementation resumption — 2026-11-27 + +## Authorization and observed baseline + +The active user goal is to implement the existing plans, preserving all requirements +and gates. This supersedes the earlier limitation to the bootstrap milestone. No +commit, push, release, sibling edit or global configuration edit is authorized. +The user confirmed that no worker is editing the existing uncommitted files and +instructed continuation from them. Preserve their intent and review them as code. + +Repository: /home/faumaray/Projects/VoidLanguageServer, main at +ca04975d545efd4a891ee90edf22f130069bd191, tracking origin/main. The committed bootstrap +and remote existed on resumption; this run did not create either. Initial changes: +cmake/VoidDependency.cmake plus15 untracked source/header files under include/Void/ +LanguageServer and src/{Documents,Protocol,Workspace}. An exact source-only backup +of these16 files is in ignored build/goal-baseline-20261127 with SHA256 manifest. +No unrelated files, secrets or sibling source were copied. + +## Delegation and branch + +The user explicitly requires Max effort and rejected XHigh. The live spawn-tool +schema fixes every approved role to XHigh and says those settings cannot be changed. +After escalation the user approved the generic runtime with explicit models and +Max, then selected GPT-6.2. The planner, researcher and independent reviewer were +dispatched under D-027. Spawn arguments record the requested model and effort. +All work continues on feat/implement-roadmap at the original base commit. + +## Immediate root integration boundary + +Roadmap01/02 was already planned, preflighted and implemented. Root may make the +small upstream compatibility repair and run its existing acceptance suites. Owned +correction: src/main.cpp. CLI modes and exit statuses remain unchanged; a sole `--` +must return usage exit2, emit no stdout and never start the LSP loop. The updated +Void Argparse accepts an end-of-options marker, so the application must reject a +successful parse that selects no mode when one argument was supplied. No alternate +parser or dependency patch is needed. The existing cli_standalone_and_invalid_modes +subprocess case already fails on exactly this input; retain its assertion. + +Dependency source remains main, without a commit pin. Ordinary reconfiguration of +the existing tree retained9931c5f despite remote main7d7d23e. CMake's population +stamps require a documented --fresh refresh. The fresh fetch resolved +7d7d23ec0a6a55d4b30921432fa215b29a29e59b. Its StrictJson now has double alternatives, +decimal/exponent grammar and a checked serializer. Existing six JSON capability +bodies pass after the fresh build. Full shell acceptance also requires the CLI +regression correction, full tests and a fresh independent integration review. + +## Existing foundation code: findings for planning + +- CMake still builds only src/{Framing,Json,Server,main}. The new Protocol, + Documents and Workspace files have no registered targets or tests; do not claim + that their presence implements roadmap03/04. +- Protocol duplicates the original vls adapter. Its temporary serializer turns + nonfinite values into null and conversion failures into zero; replace this with + the now-available checked upstream API and an explicit failure contract before use. +- Documents has immutable shared snapshots, ordered edits, URI handling and encoding + conversion. The code currently rejects character positions beyond line length; + LSP requires clamping them. Preserve rejection of split scalars/surrogate pairs. + Test CR/LF/CRLF, full-text recovery, stale changes, aliasing and concurrent reads. +- Document disk reads release the store lock before I/O. Recheck overlays/revision + after the read so a newly opened/changed overlay cannot be bypassed by publication. +- Workspace configuration exists; TrustPolicy and tool inspection are declarations + without an implementation. Default wrapper names are data recognition only, never + authority to execute them. Repository configuration cannot grant trust. +- Freeze BuildContext/AnalysisRevision and source identity contracts before providers, + schedulers or semantics. Avoid an unreviewed namespace migration; integrate the + existing Void::LanguageServer namespaces deliberately. + +These are root inspection findings, not an independent review verdict. Graph +identity/freshness was checked. Relevant VLS paths mostly match metadata; partial +header ranges and all important claims were checked against source. VoidLibrary's +graph was stale, so its exact StrictJson source was read directly without reindexing. + +## Evidence sources and next gates + +[LSP3.17 positions](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#position) +defines encoding negotiation, line endings and oversized character clamping. +[CMake CMP0168](https://cmake.org/cmake/help/latest/policy/CMP0168.html) documents +--fresh forcing dependency download/update/patch steps with the current policy. + +VBS has advanced to6c225c2dff58b64fe8dbb0e5072f8e23f566efe5 and has an Editor CompDb +API, immutable profile generations, selection state and IDE query/config functions. +Its working tree is actively changed and not owned here. These APIs are evidence +to assess for roadmap06, not proof that the complete required tooling manifest or +live native integration already exists. Do not copy its private workspace metadata. + +The CLI repair passes both bootstrap builds. A coherent VBS seed built from the +committed 6c225c2 source successfully built and ran the native decimal probe. +VBS also emitted an immutable debug compilation database with both main.cpp and +the host build.cpp context. The next work is the primary native VLS build and +foundation integration, with the full frontend, debugger and editor gates retained. diff --git a/docs/agent-workflow/REVIEW.md b/docs/agent-workflow/REVIEW.md index b7c4c44..ab4a2a1 100644 --- a/docs/agent-workflow/REVIEW.md +++ b/docs/agent-workflow/REVIEW.md @@ -1,5 +1,75 @@ # Integrated review record +## Recorded adapter and stock GCC data + +The independent GPT-6.2 Astra review found a truncated recording whose +frames could be listed on the timeline but could never be opened as a cursor. +The adapter now opens a nonempty recording with no integral return at its +last verified event. A second response sharing a deferred launch sequence, +orphaned launches on malformed input and replies to non-request packets +were corrected and reproduced through stdio. The review also verified +negotiated variable paging, uint32 page offsets, typed breakpoints, the +single-owner cursor, terminal state and rejection of no-debug launches. +Seven registered cases run against the executable or its shared session. +Additional transcripts use the three real GCC recordings. The reviewed +binary and native installation evidence are recorded in VERIFICATION.md. + +The independent semantic review closed all four findings in the diagnostic +decoder, GCC fixture and module planner. Combining characters and joiners +with ambiguous display columns preserve the message as unlocated. A malformed +SARIF artifact index cannot authorize an empty clear. Relative GCC path +aliases preserve both spaces and literal percent escapes. A non-interface +named provision can supply an internal partition only when its module name +contains a partition qualifier. Stock GCC and the two C++ suites supplied +the positive controls. + +## Provider and compiler corrections + +The independent provider review found incorrect translation-unit selection +through symlinks and parent components, coupling between independent locator +grants, an untracked missing response file, command quoting differences, and an +installed-transcript validator that rejected a valid 17-owner listing. The +corrections have runnable provider, stdio and installed tests. A second review +identified nonexistent path components followed by `..` and a malformed unused +locator. Root added distinguishing cases and verified both builds. Automatic +content review stopped that review assignment before a final verdict. + +The independent private compiler review reproduced a BOM shifting a function +occurrence onto a same-named namespace qualifier. The reviewer later hit HTTP +429. Patch 0003 now passes that real regression, including a first-line +definition referenced on another line. Final independent approval of the +integrated compiler and provider changes remains open. + +## Integrated foundations on November 27 + +T-REVIEW-005 reproduced a disk snapshot containing bytes from two file states. +The document store now checks the stable opened object and revalidates the named +file before publishing. A deterministic case changes a multi-chunk read and +separately replaces its inode before publication. It passes in both builds. + +Malformed identifiable change notifications now mark the open document +desynchronized. Dependency preparation rejects tracked translation units omitted +by its input rules. The installed binary runs the negotiated edit transcripts +outside the workspace. A fourth correction accelerates same-line endpoints while +preserving Unicode boundary checks. The independent correction review remains due. + +## November 27 bootstrap review + +T-REVIEW-003 independently accepted the CLI repair. It reproduced two JSON +defects on VoidLibrary main `7d7d23e`, despite all 37 earlier cases passing. +The bootstrap JSON verdict is **CHANGES_REQUIRED**. + +| Finding | Evidence from the stdio executable | Acceptance | +| --- | --- | --- | +| P1, ID precision | After initialize, id `1.0000000000000001` shut down the server as id `1`. A subsequent shutdown with id `1` was rejected. | Reject the fractional ID with null correlation and keep the session running. Accept the following integer ID. | +| P2, valid numbers outside machine range | id `9223372036854775808` and an ignored initialization option `1e-400` both caused ParseError. | Return InvalidRequest for the ID, accept the ignored option and keep ParseError for invalid syntax such as `1e`. | + +StrictJson converts decimal tokens to double before returning its DOM and +rejects out-of-range conversions. The public DOM has no source span or numeric +token accessor. Two ordinary regression cases now exercise these requirements. + +## November 25 bootstrap review + Date: 2026-11-25. Scope: approved initial milestone, main with unborn HEAD. Reviewer role: astra_reviewer, configured XHigh; runtime model not independently verified. The reviewer did not implement the changes and had read-only ownership. diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 41215d8..70c630d 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,33 +1,214 @@ # Development state -Updated: 2026-11-25 -Repository: /home/faumaray/Projects/VoidLanguageServer -Branch: main; HEAD: unborn -Stage: AWAITING_UPSTREAM — independent scope reviewed; final JSON acceptance blocked -Baseline: only .serena runtime metadata; preserved and ignored. -Git initialized locally; no stage/commit/remote/push. +Updated December 5, 2026. Work is on `feat/implement-roadmap` at +`ca04975d545efd4a891ee90edf22f130069bd191`, with implementation changes in the +working tree. The user authorized all 27 plans on this branch. The 16-file +original foundation baseline is preserved under `build/goal-baseline-20261127`. +VoidLibrary follows main; the current prepared generation is +`9cb86f8f978668215328ead51ee6f132552847c1`. -## Delivered work -Root: 27 plans, requirements, architecture and decisions written; T-001 handed -source ownership back. Upstream and local-override builds pass. Unit/process tests -pass (31 cases); six JSON capability cases fail on the actual upstream limitation. -Initial review found unmatched-response handling and incorrect numeric-ID test -expectations; both are corrected and cleared by T-REVIEW-002. Independent scope -verdict READY; final JSON acceptance CHANGES_REQUIRED. See REVIEW.md and -VERIFICATION.md for evidence. Implementer and reviewer are closed; no active workers. +## Verified -## Prerequisites -VoidLibrary inspected HEAD: 9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5. -Upstream decimal support is not implemented yet, confirmed by the user. D-021 -selects following main WITHOUT a commit pin; the fetched/tested commit remains -the baseline above. Reconfigure to check main, inspect its API and run the full -suite before closing final JSON integration and shell acceptance. -Semantic/backend, debugger and native VBS capabilities remain planned. +* VoidBuildSystem builds VLS and VoidLibrary natively. Preparation follows + VoidLibrary main and records each selected immutable generation. The staged + executable from the development VBS install path passed a real stdio session. +* The stdio server negotiates UTF-8 or UTF-16, owns immutable document overlays + and accepts ordered incremental edits. It advertises text synchronization. + Both encodings were exercised through an edit whose outcome depends on the + previous replacement having actually taken effect. +* Native VBS and comparison CMake each register 266 C++ cases across ten suites. + All registered cases pass on VoidLibrary `9cb86f8f`, including the two exact + numeric request ID and out-of-range JSON number cases that failed on + `7d7d23e`. The upstream StrictJson defect was reported as Void/Library#60 and + closed after the fix was verified. All eight dependency preparation tests pass. + [Verification commands and results](VERIFICATION.md) +* Installed VLS reports per-document contexts from the selected VBS generation + and from an external compilation database. Real stdio tests cover aliases, + including a symlink followed by a parent component, a change of file identity, + unavailable optional locators and the 16-alternative response limit. +* Reference GCC 16.2 passed the 19-case reflection and module corpus. The + pinned Bloomberg compiler built successfully. It accepted the basic module, + splice and range-expansion controls and failed the production Void header and + GCC standard-library fidelity checks. GCC 16.2 resolved both edited overloads + and recovered from an invalid edit. Two private module generations produced + distinct reflected values. The user authorized an isolated GCC worker and + versioned evaluator hooks. -## Next concrete action -When upstream main changes, rerun the default configure command, record its actual -fetched commit, inspect StrictJson's numeric API and adapt only the thin VLS boundary -if necessary. Build and run all four CTest entries, inspect all six JSON capability -bodies and re-review representation/range behavior. Do not accept the full shell -while any required case fails, restore a pin, or patch a sibling repository. -The final main check still returned9931c5f. No persistent watcher was created. +## In progress + +Module work now has an editor admission path: `ModuleWorkQueue` submits scans +at background priority and artifact preparation at artifact priority on the +same bounded Scheduler used by analysis. A newer revision supersedes queued +work and cancels running work, and the EditorDiagnostics lifecycle cancels both +kinds per document on edit/close and on shutdown. The registered module suite +covers priority separation, supersession, per-document cancellation, stale +revisions and terminal counts. `EditorDiagnostics` now builds the checked P1689 +scan command from the active compiler context and submits it through the +queue; `analysisStatus` reports the decoded provides/imports. The real stdio +corpus reached `moduleScan: ready` on the Void TU. The module corpus now drives artifact preparation from the decoded scan rule and +asserts a published generation; editor-driven artifact +production is verified: `tests/native/EditorModules.py` observed `editor.cmi` from the +scan and a published 64-character artifact generation through `EditorDiagnostics`. + +Live DAP control for the private GCC worker is implemented: `LiveSession` +spawns the worker, speaks its notice/control protocol, tracks stop generations +and enforces bounded notices and deadlines; `vls-dap --live` maps DAP +`continue`/`next`/`disconnect` to worker control, maps `setBreakpoints` to the +live session with hit IDs on matching stops, projects typed values from the +inspection snapshot, rejects `pause`/`stepIn`/`stepOut` explicitly, and serves +bounded frame and state inspection with handles that expire when the session +moves. The registered `vls_live_tests` +suite covers stepping, inspection per generation, continue, cancel, refusal +without a stop, malformed output and the deadline, and a real DAP transcript +test drives the adapter end to end. + +Completion is now served: `textDocument/completion` is advertised and answered from the symbol index through `EditorDiagnostics::completion`, with a bounded ranking core in `include/vls/features/` and registered `vls_feature_tests`. Results are explicitly incomplete because the index does not prove visibility; compiler-native completion, deferred detail resolution and signature help remain open. + +Index-backed rename coverage is now merged into the navigation fact set (`vls/features/IndexNavigation.hpp`): persisted index contexts and records join the set with the index's completeness, existing compiler-derived facts win, and records without a known current content identity stay non-editable so rename refuses them. Multi-file rename can therefore be ready from real index data when a transactional client is present, proven by registered `vls_feature_tests` cases. + +The rename transaction is now applied in both editor clients. Neovim's +`:VlsRename` requests the guarded server rename and applies the `changes` map +transactionally: every range is validated before any buffer is touched, edits +are applied per buffer, and any failure restores the exact pre-edit lines and +modified state of every already-changed buffer. VS Code registers a C++ rename +provider backed by the server and exports `applyRename`, which builds one +`WorkspaceEdit`, rechecks the document versions captured at preparation, and +relies on VS Code's transactional application. Headless tests inject a buffer +write failure (Neovim) and a stale document version (VS Code) and assert no +partial edits. + +The navigation and guarded-rename package (roadmap 16) is implemented with a +registered suite: binding resolution that never resolves overlapping spellings +by iteration order, deduplicated references with explicit coverage, and a +rename plan that refuses incomplete coverage, stale sources, non-editable +origins, ambiguous bindings, generated/invalid names and multi-file edits +without a transactional client. `textDocument/references`, +`textDocument/prepareRename` and `textDocument/rename` are wired to it. The +stock occurrence corpus asserts that references, prepareRename and rename all +refuse with an explicit incomplete-coverage error rather than returning an +apparently complete set. Applying a ready multi-file rename through client +buffer transactions remains open. + +The context-aware symbol index (roadmap 15) is implemented as a bounded +library with a registered suite: explicit analysis contexts, unsaved overlays +that shadow committed records and reconcile on save/close, dependency and +source invalidation that marks coverage incomplete without discarding last-good +records, immutable generations with reader retention, versioned persistence +(schema 2 with a payload digest, migrating schema-1 snapshots on restore) +with corrupt/incompatible/oversized rejection and quarantine, and bounded queries reporting +coverage and truncation. It is wired into navigation: `EditorDiagnostics` +ingests occurrence facts after each analysis and the server answers +`workspace/symbol` from the index; the stock occurrence corpus found the +Hash.hpp definition through it. Real persistence migrations and cross-file +rename coverage remain open. + +Index-backed completion (roadmap 14 first slice) is implemented: `include/vls/features/Completion.hpp`, `src/features/Completion.cpp` and registered `vls_feature_tests` cover prefix extraction, filtering with replacement ranges, label+kind deduplication, deterministic ranking and bounds. `Server.cpp` advertises `completionProvider` and answers `textDocument/completion` from the symbol index through `EditorDiagnostics::completion`; a real stdio session with the stock observer returned `fnv1a64` and `fnv1a64_update` at a real call site. Every result is marked incomplete because the index does not prove visibility. Signature help is now served from the compiler-provided occurrence signature (parameter labels and ranges, active parameter, innermost call selection) and advertised by the server. Compiler-native completion with visibility proof and deferred detail resolution remain open. + +The reflection provenance representation (roadmap 12 first slice) is +implemented as a bounded library with a registered suite: innermost-first +origin chains distinguishing editable spelling, expansion/splice sites, +reflected declarations and synthesized entities (generated entities stay +navigable but not automatically renameable), variant values with canonical +types and honest opaque/unavailable kinds, depth-first expansion that reports +cycles, depth/value-limit cuts and dangling references instead of dropping +them, a versioned canonical JSON snapshot with duplicate/oversized/incompatible +rejection, and a proposal/facility capability matrix where an unknown entry is +an explicit error. Read-only virtual generated views render an entity and its +expansion as explanation lines with source links, explicit cycle/truncation +markers and a never-compilable contract. Compiler extraction of splice origins +is now real: patch 0004 makes the reproduced GCC record the splice site and the +designated entity, the worker trace exposes them in inspection snapshots, and a +registered test asserts the provenance chain from recorded real compiler +output. LSP-shaped `hover`/`locations` adapters exist in the reflection library, +and the live DAP `variables` projection exposes reflected entities with their +declaration and splice coordinates. The `EditorDiagnostics` LSP path and +index/rename integration remain open because the server has no reflection data +source yet. + +The bounded analysis scheduler (roadmap 10) is implemented as a library with a +registered suite and is now the admission layer of `EditorDiagnostics`: one +foreground slot preserves the single compiler-state owner, revision coalescing +supersedes queued work, running work receives cooperative cancellation, the +watchdog bounds stalled jobs, and `analysisStatus` exposes the scheduler +counters. Separate foreground, background and artifact pools, queue and memory +admission, exactly one terminal completion per accepted submission, and a +drain that waits for in-flight completions are covered by the suite. The +private module artifact store (roadmap 11 ownership) is also implemented: +content-addressed all-or-nothing generations, reader retention, bounded +eviction and dependency-ordered production from a ready `ModulePlan`. Real GCC +CMI production runs the selected compiler per planned unit in a private +working directory and module cache, verifies the single produced CMI and +publishes it through the cache. Module artifact preparation also runs through +the bounded Scheduler at artifact priority: a superseded build is cancelled and +publishes nothing, and the module corpus asserts both outcomes with the real +compiler. Both suites pass in VBS and CMake, and the scheduler suite is clean +under the sanitized profile (address and undefined sanitizers) across repeated +runs. + +Both thin editor clients are implemented and tested against the real +services. `clients/neovim/` with `tests/native/NeovimClient.lua` passed on +Neovim 0.12.6 and nvim-dap `cfa2d58`, and `clients/vscode/` with +`tests/native/VscodeClient.py` passed in a disposable extension host on VS Code +1.147.0. Both cover LSP status, a replay session, bounded timeline paging, +captured source and stale-generation rejection. Live debugging, guarded rename +and the remaining semantic features keep their separate gates. + +The local stock GCC observer (T-STOCK-OCCURRENCES-014) is delivered with its +build tool and closed verifier: `experiments/frontend/gcc-observer/Observer.cpp`, +`tools/prepare-gcc-observer` and `tests/corpus/frontend/verify-stock-observer.py`. +It publishes compiler-owned direct-call return types, canonical types, +signatures and joined function definitions as strict JSON with byte-checked +spans. The verifier covers same-line overloads and edits, header shifts and +recovery, macro and `#line` withholding, same-name qualifiers, declared-only +targets, template instantiations, UTF-8 BOM, paths with spaces, capacity, +compile errors, malformed manifests and a sealed fixed-path run. The host +integration is also tested: the launcher profile selects the observer by path +and SHA-256, each job re-verifies the staged bytes, `decode_occurrences` +validates the report against the exact capture, and LSP hover/definition serve +the verified facts. `tests/native/StockOccurrences.py` selected the +`string_view` overload at Hash.hpp:59 and the `byte_span` overload at line 65 +after editing the real Void call. Constant-folded calls are withheld because +the frontend removes them before genericization. + +The C++ module planner passed 21 cases, including a stale header-unit CMI, +an added file changing `__has_include`, duplicate providers and a 4,096-unit +chain. The GCC corpus checked 33 scanner and module behaviors. Seven integration +cases exercised the C++ planner, including a changed partition graph and a +failed scan that still produced a rule. Editor scheduling and private module +artifact production remain open. + +The VBS-installed executable and the comparison executable both deliver stock +GCC 16.2 diagnostics over LSP with the opt-in Linux/Nix profile. The installed +server selected the correct main TU among 54 native and 76 comparison commands. +The stdio corpus edited the real VBS-selected `DocumentSnapshot.cpp` and received +the correct seven-character error range on line 19. Fixing the source cleared +the error. A superseded compile produced no late notification. Initial source +discovery used ten frontend passes, and the subsequent edit used one. A +compilation-database workspace also exercised an unsaved header, an optional +header appearing on disk and a `#line` remap with an unlocated error. + +The editor can request `voidLanguageServer/analysisStatus` for the current +TU's context and unlocated messages. Larger workspaces, cross-file diagnostic +publication, additional toolchains and module scheduling remain open. The C++ +diagnostics suite includes ten SARIF and sixteen source-catalog tests. + +The private GCC 16.2 frontend passed 19 language checks, eight tooling probes +and 33 module checks with the reference standard library and flags. Its first +local patch captured a nested return of 17 followed by 34, then 41 followed +by 82 after an enum edit. The same compiler process paused, stepped and +resumed. Cancellation preserved the observed inner result. The prototype +supervisor and offline replay passed their process checks. Both builds pass +13 journal cases and eight immutable recording cases. Offline replay reproduced +four real recordings, including a four-stop session and cancellation. The +source-occurrence harness passed after patch +0003 corrected first-line physical columns for UTF-8 byte-order marks. +The stock GCC/GDB experiment also observed the nested returns on one +unmodified compiler package. Production +compiler-backed IDE features, debugging protocols, editor clients and adoption +retain their separate acceptance gates. + +The user approved GPT-6.2 Astra/Sol at Max for all delegated tasks. Runtime +responses identify the requested assignment and thread, without independent +model or effort attestations. Some assignments returned HTTP 429. The root +verified the available files and test outcomes and recorded outstanding reviews +in [TASKS.md](TASKS.md) and [PREFLIGHT.md](PREFLIGHT.md). diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 1b1a733..6ebd321 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -1,16 +1,72 @@ # Task graph and ownership -Baseline: main, unborn HEAD. Shared checkout; no isolated worktrees. +Baseline: ca04975d545efd4a891ee90edf22f130069bd191. Current branch: +feat/implement-roadmap (user requested). Shared checkout; no isolated worktrees. +The original writer released the foundation files. Current ownership follows. | Task | Status | Owner | Exclusive writes/dependencies | | --- | --- | --- | --- | | T-ROOT-INIT | COMPLETE | Root Astra | Git initialization, AGENTS.md, .gitignore | -| T-DOC | COMPLETE_REVIEWED | Root Astra | README.md, docs/; 27 plans, contracts and local links reviewed | -| T-001 | PARTIAL_UPSTREAM_GATE | Root after Sol handoff | Source/build/tests implemented; 31 cases pass, 6 upstream JSON capability cases fail | -| T-JSON-MAIN | BLOCKED_UPSTREAM | Root | Follow main per D-021; record tested commit; complete JSON suite must pass | -| T-INTEGRATE | PARTIAL_UPSTREAM_GATE | Root Astra | Both build modes, install and independent scope verified; final JSON gate remains | -| T-REVIEW | COMPLETE | Independent astra_reviewer, closed | T-REVIEW-002: independent READY, full acceptance CHANGES_REQUIRED; see REVIEW.md | +| T-DOC | UPDATING | Root Astra | Full implementation authorization, native VBS priority, branch and current evidence | +| T-001 | REVIEWED | Root | CLI usage regression fixed and accepted. The JSON gate has separate ownership below. | +| T-JSON-MAIN | COMPLETE | Root | VoidLibrary main `9cb86f8f` fixes both exactness/range regressions. All 266 native cases pass; Void/Library#60 closed after verification. | +| T-INTEGRATE | IN_PROGRESS | Root Astra | Bootstrap update tested; new independent review required | +| T-REVIEW | HISTORICAL_COMPLETE | Independent astra_reviewer, closed | T-REVIEW-002 covers the November 25 bootstrap | +| T-PLAN-002 | COMPLETE | astra_planner | Native build and foundation contracts passed to preflight | +| T-RESEARCH-008 | COMPLETE | astra_researcher, closed | GCC reference findings. Root owns tests/corpus/frontend and the exact candidate experiment. | +| T-REVIEW-003 | COMPLETE | astra_reviewer | CLI accepted, JSON precision and range defects reproduced | +| T-PREFLIGHT-004 | REVIEWED_WITH_AMENDMENTS | astra_reviewer, closed | Four slices accepted. Root incorporated the session and model corrections. Follow-up reviewer hit HTTP 429. | +| T-NATIVE-001 | SPLIT | Root | First Sol assignment received HTTP 429 before edits. Root owns build.cpp, test registration, build and installation. | +| T-NATIVE-PREP | INTEGRATED | astra_implementer, closed; root integrates | Immutable dependency inputs. All eight preparation tests pass, including unsupported tracked source names. | +| T-PROTOCOL-005 | INTEGRATED | sol_implementer, closed; root integrates | Canonical Protocol and compatibility headers, checked server egress and seven new tests. Both builds tested. | +| T-DOCS-003 | INTEGRATED | sol_implementer, closed; root integrates | 18 Documents cases, including disk-read coherence. | +| T-TRUST-004 | INTEGRATED | astra_implementer, closed; root integrates | 17 workspace cases, scoped tool approval/revocation and configuration origins. | +| T-SESSION-003 | INTEGRATED | Root | Negotiation, checked server lifecycle, document notifications and two actual process transcripts | +| T-MODEL-005 | INTEGRATED | astra_implementer, closed; root integrates | Immutable generations, context selection and publication. All 18 tests pass, including incomplete affected-context rename. | +| T-PLAN-006 | COMPLETE | astra_planner, closed | Actual VBS v1 and compdb data, relative locators, tool authority, session and publication plan. | +| T-REVIEW-005 | CHANGES_ADDRESSED | astra_reviewer, closed | Root corrected disk-read coherence, malformed envelopes and preparation coverage, and repeated installed transcripts. Independent re-review remains due. | +| T-DOCS-PERF-006 | INTEGRATED | sol_implementer, closed | Constant-space line scanning and four LongLines cases. Both builds include them. | +| T-PREFLIGHT-007 | REVIEWED_WITH_AMENDMENTS | astra_reviewer, closed | All four provider contracts cleared after the Astra retry. | +| T-PROVIDER-IO-007 | FOCUSED_TESTS_PASSED | Root after an HTTP 429 | ProviderFile.cpp and ProviderFileTests.cpp. Seven acquisition cases passed. | +| T-PROVIDER-ROWS-007 | INTEGRATED | Released to root | Typed checked rows, file-language proof, path identities and response dependencies. | +| T-PROVIDER-VBS-006 | INTEGRATED | Root | VbsProvider.cpp and CompdbProvider.cpp with direct selected-generation and fallback checks. | +| T-PROVIDER-SESSION-007 / T-SESSION-PASSIVE-007 | INTEGRATED | Released to root | Stdio status, settings, last-good history and bounded alternatives passed the installed transcripts. | +| T-REVIEW-PROVIDER-007 / T-REREVIEW-PROVIDER-007 | CORRECTIONS_TESTED | Root | Both reviews identified incorrect physical paths or optional grants. The second review ended before a full verdict. Results are recorded in REVIEW.md. | +| T-PLAN-GCC-008 | COMPLETE | astra_planner, closed | Version-bound evaluator, parser, source provenance and supervisor contracts. | +| T-CORPUS-MODULES-011 | VERIFIED | sol_implementer released, root verified | Reference and privately built GCC ran 33 scanner/module checks. | +| T-PREFLIGHT-GCC-008 | REVIEWED_WITH_AMENDMENTS | astra_reviewer, closed | Integral evaluator, fixed launcher, bounded control/replay, and narrow IDE use/definition hooks cleared. | +| T-GCC-EVALUATOR-017 | VERIFIED | astra_implementer released, root verified | Versioned GCC patch 0001 and actual private compiler harness. Returns, pause, step, cancellation and truncation observed. | +| T-GCC-LEAF-009 / T-GCC-SUPERVISOR-018 | PROTOTYPE_VERIFIED | Released to root | Native private-compiler launch, same-process control, cancellation and recorded trace. | +| T-GCC-TRACE-019 | INTEGRATED | Root | Thirteen offline trace cases in both builds. | +| T-GCC-IDE-008 / T-REVIEW-GCC-019 | CORRECTION_TESTED | Root | Patch 0002 exercises narrow typed occurrences. Patch 0003 corrects BOM-relative physical source positions; a complete fresh review is due. | +| T-GCC-PREP-008 | PENDING | Unassigned | Opt-in private compiler reproducer; previous Sol attempts returned HTTP 429. | +| T-PLAN-SEMANTICS-010 | COMPLETE | astra_planner, closed | Stock GCC accepted the real Void TU and its overload edit, reported a source error, and identified the edited header overload. | +| T-PREFLIGHT-MODULE-011 / T-MODULE-GRAPH-011 | INTEGRATED | Released to root | C++ P1689 decoder, closed census, graph planning and reverse dependencies. All 21 unit cases pass. | +| T-MODULE-CORPUS-011 | VERIFIED | Root | Seven C++ planner cases driven by the actual GCC module corpus, including failed scan and header CMI controls. | +| T-PREFLIGHT-DIAGNOSTIC-013 / T-DIAGNOSTIC-SARIF-013 | VERIFIED | Root after an HTTP 429 | Ten adapter cases plus an actual edited Void translation unit using the native-built fixture and stock GCC. | +| T-PREFLIGHT-LEASE-009 / T-SEMANTIC-LEASE-009 | INTEGRATED | Released to root | All 17 new cases pass in both builds. The stock diagnostic fixture uses the same checked selection API on native and comparison metadata. | +| T-PREFLIGHT-SOURCE-009 / T-SOURCE-OVERLAYS-009 | INTEGRATED | Root verified after implementer returned HTTP 429 | Fourteen bound-input cases cover the editor census, disk eligibility and current selection. | +| T-PREFLIGHT-CATALOG-009 / T-SOURCE-CATALOG-009 | INTEGRATED | Root | Explicit source roots, positive and negative exact lookups, and disk/overlay validation. All 14 cases pass in both builds. | +| T-STOCK-EDITOR-013 | INTEGRATION TESTS PASSED | Root | Opt-in GCC 16.2 profile, isolated lookup discovery, current-context publication and background revalidation passed the comparison and VBS-installed stdio corpora. Broader worker integration and independent review remain open. | +| T-PLAN-DAP-020 / T-PREFLIGHT-REPLAY-020 / T-REPLAY-RECORDING-019 | INTEGRATED | Root verified the completed files after the worker hit HTTP 429 | All eight immutable recording and 13 legacy journal cases pass in both builds. The real supervisor and four offline recordings also passed. DAP integration follows. | +| T-REVIEW-SEMANTIC-013 / T-FIX-DIAGNOSTIC-COLUMNS-013 | REVIEWED | Released to root | Independent Astra reviewed the repaired decoder, literal producer path handling and module provision check. CMake passed 29 diagnostic/catalog and 22 module cases. | +| T-PREFLIGHT-DAP-020 / T-DAP-TRANSCRIPTS-020 | INTEGRATED | Root | Preflight covered initialization, recorded values and source representation. Sol supplied four registered cases before HTTP 429. Root added three cases and interactive Python and Neovim transcripts. | +| T-REVIEW-DAP-020 | REVIEWED | Independent Astra, released to root | Rechecked all reported source, prefix, lifetime, paging and transport findings on the CMake executable. Root owns the final native transcript. | +| T-PLAN-STOCK-NAVIGATION-014 | FEASIBILITY WITNESSED | astra_planner | A stock GCC 16.2 plugin distinguished the real Void header overloads, a header line shift, a broken edit and recovery in a sealed view. | +| T-PREFLIGHT-STOCK-NAVIGATION-014 / T-STOCK-OCCURRENCES-014 | PRODUCER_IMPLEMENTED_TESTED | Root | Stock GCC observer, scrubbed build tool and closed verifier delivered. Dynamic-section validation rejects the planner's mutable RUNPATH. | +| T-OCCURRENCES-HOST-014 | IMPLEMENTED_TESTED | Root | Launcher profile observer selection, per-job byte verification, strict capture-bound decoder, LSP hover/definition and a real stdio corpus (`tests/native/StockOccurrences.py`). | +| T-SCHEDULER-010 | IMPLEMENTED_TESTED | Root | `include/vls/scheduler/`, `src/scheduler/` and `vls_scheduler_tests`. Foreground/background/artifact pools, admission, coalescing, cancellation, watchdog and metrics. Integrated into `EditorDiagnostics`; `StockOccurrences.py` observed a superseded running revision cancelled. | +| T-MODULE-ARTIFACTS-011 | IMPLEMENTED_TESTED | Root | `ArtifactCache`, `produce_module_artifacts`, `gcc_module_artifact_work` and scheduler-driven `produce_module_artifacts_scheduled` in `src/modules/`. Registered tests cover publication, retention, eviction, ordering and supersession; the module corpus produces a real GCC CMI, consumes the published copy, rejects a truncated CMI and asserts a superseded build publishes nothing. Editor scheduling remains. | +| T-INDEX-015 | IMPLEMENTED_TESTED | Root | `include/vls/index/`, `src/index/` and registered `vls_index_tests`: contexts, overlays, invalidation, generations, persistence and bounded queries. Wired to `workspace/symbol` through `EditorDiagnostics`; the stock occurrence corpus reached the Hash.hpp definition. `restore` now quarantines incompatible/corrupt snapshots and rebuilds a generation. Snapshots are schema 2 with a canonical payload digest; schema-1 snapshots migrate on restore and the generation backend persists the upgrade, with registered migration and corruption cases. | +| T-NAVIGATION-016 | IMPLEMENTED_TESTED | Root | `include/vls/navigation/`, `src/navigation/` and registered `vls_navigation_tests` (label `navigation-rename`): unique/ambiguous binding resolution, deduplicated references with coverage, and guarded rename refusing incomplete coverage, stale sources, non-editable origins, multi-file without a transaction and invalid names. `textDocument/references`, `prepareRename` and `rename` are wired; the stock corpus asserts the incomplete-coverage refusals. Neovim `:VlsRename` and the VS Code rename provider apply ready plans transactionally with rollback/version preconditions tested. Index-backed facts are now merged into the navigation set (`vls/features/IndexNavigation.hpp`), so multi-file rename can be ready from persisted index coverage when a transactional client is present; unknown-source records stay non-editable. | +| T-MODULE-EDITOR-SCHEDULING-011 | IMPLEMENTED_TESTED | Root | `ModuleWorkQueue` in `src/modules/` admits scans at background priority and artifacts at artifact priority on the editor Scheduler, with revision coalescing and per-document cancellation wired into `EditorDiagnostics`. Registered tests cover priority separation, supersession, cancellation, stale revisions and counts. `EditorDiagnostics` now derives the checked P1689 scan command from the active compiler context (`build_scan_invocation`), submits it through `ModuleWorkQueue`, and records the decoded provides/imports in `analysisStatus`. The real stdio corpus reached `moduleScan: ready` on the Void TU, and the module corpus ran `corpus.cmi` through the queue. The module corpus asserts a published artifact generation produced from the decoded scan rule through `produce_module_artifacts_scheduled` at artifact priority. Artifact preparation is now submitted from `EditorDiagnostics` itself, and `tests/native/EditorModules.py` passed end to end against the native VBS server and the refreshed installed server: the scan provided `editor.cmi` and a 64-character artifact generation was published. | +| T-LIVE-DAP-018 | IMPLEMENTED_TESTED | Root | `include/vls/debug/live/`, `src/debug/live/` and registered `vls_live_tests` (label `live-debug`): worker protocol, stop generations, step/continue/cancel, bounded inspection, malformed output and deadlines. `vls-dap --live` is covered by `tests/native/LiveDap.py` (stopped, typed value projection, setBreakpoints mapping with hit IDs, step, stale handle rejection, continue, pause refused) and the registered C++ suite asserts the typed projection (`stackTrace`/`scopes`/`variables`, `Result = 17`). Template/reflection stepping against the reproduced private compiler passed `tests/native/GccSupervisor.py`. | +| T-REFLECTION-012 | PARTIAL | Root | Roadmap 12 representation and extraction slices: `include/vls/reflection/`, `src/reflection/` and registered `vls_reflection_tests` (label `reflection`, 24 cases): versioned provenance chains, honest value kinds, bounded expansion with cycles, canonical JSON persistence, a capability matrix, read-only virtual generated views, LSP-shaped `hover`/`locations` adapters, and real splice-origin extraction (patch `0004-splice-origins.patch`, worker `origins`, `snapshot_from_splices`). The live DAP `variables` projection exposes reflected entities with declaration and splice coordinates, asserted by `vls_live_tests` from a real-shaped origin. `EditorDiagnostics` LSP wiring remains open because the server has no reflection data source; index/rename integration also remains. | +| T-COMPLETION-014 | PARTIAL | Root | `include/vls/features/Completion.hpp`, `src/features/Completion.cpp` and registered `vls_feature_tests` (label `completion-hover`, 6 completion cases plus 7 index-navigation cases): bounded ranking core, `textDocument/completion` wired through `EditorDiagnostics::completion` to the symbol index. Results are explicitly incomplete; compiler-native completion, visibility proof and deferred detail resolution remain open. `textDocument/signatureHelp` is also implemented from the compiler-provided occurrence signature (parameter labels/ranges, active parameter, innermost-call selection), and the server advertises it; a real stdio session on `add(1, 2)` returned `int add(int, int)` with activeParameter 0 then 1. | +| T-PLAN-EDITORS-022 | COMPLETE | Root | Verified Neovim 0.12.6, nvim-dap cfa2d58, VS Code 1.147.0, Node 24.22.3. Two ownership-ready contracts: [T-CLIENT-NEOVIM-023](tasks/T-CLIENT-NEOVIM-023.md) and [T-CLIENT-VSCODE-022](tasks/T-CLIENT-VSCODE-022.md). | +| T-CLIENT-NEOVIM-023 | IMPLEMENTED_TESTED | Root | `clients/neovim/` and `tests/native/NeovimClient.lua` passed with the installed server, adapter and nvim-dap. VS Code client remains. | +| T-CLIENT-VSCODE-022 | IMPLEMENTED_TESTED | Root | `clients/vscode/` and `tests/native/VscodeClient.py` passed in a disposable extension host with VS Code 1.147.0. | -Jev's sol_implementer candidate matches T-001. Root handles docs concurrently. -T-001 completed handoff; root now owns source/build paths. All workers are closed. -All future roadmap ownership is proposed, not an active worker assignment. +Per D-027 the generic runtime uses an explicit GPT-6.2 model and Max for each +assignment. The suggested Sol implementation assignment follows planner/preflight. +Full-roadmap ownership remains proposed until exact tasks and required preflight. diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index 3c7d11e..da2dd6f 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -1,8 +1,958 @@ # Verification evidence -Updated: 2026-11-25. Builds and independent shell suites pass; final JSON acceptance is blocked upstream. +## December 5 private compiler stepping and index recovery + +The reproduced private GCC 16.2.0 frontend (stripped of debug info to fit the +leaf's executable-image bound) ran under the sealed supervisor: + +```sh +strip --strip-debug build/private-gcc/build/gcc/cc1plus +dev cpp-gcc -c python3 -B tests/native/GccSupervisor.py \ + --probe "$PWD/build/native/profiles/debug/out/bin/vls_gcc_probe" \ + --cc1plus "$PWD/build/private-gcc/build/gcc/cc1plus" +``` + +Observed: `Live and offline GCC sessions agree on 17/34 and 41/82, stale +controls and cancellation` and `Verified truncated input, bounded stderr, +running cancellation and leader-first process cleanup`. + +`vls_index_tests` passed 20 cases including +`generation_backend_recovers_a_missing_current_file`: a missing current +generation file is recovered from the previous generation and promoted back. + +## December 5 reflection provenance representation + +Roadmap 12 now has its bounded representation slice: `include/vls/reflection/`, +`src/reflection/` and the registered `vls_reflection_tests` (label `reflection`, +20 cases) covering the innermost-first origin chain (spelling, expansion, +splice, reflected declaration, synthesized) with the rename policy that a +generated entity may stay navigable while never being automatically editable; +variant values with canonical types and honest `opaque`/`unavailable` kinds; +bounded depth-first expansion that reports cycles, depth/value-limit cuts and +dangling entity references instead of silently dropping them; a versioned +canonical JSON snapshot with round-trip identity, duplicate rejection and +oversized/incompatible-byte rejection; a proposal/facility capability matrix +where an unknown entry is an explicit error; and read-only virtual generated +views that render an entity and its expansion as explanation lines with source +links, explicit cycle/truncation markers and a `compilable() == false` +contract. The private compiler's inspection frames report evaluator frames +(name, source, line, value) but no reflection origin kinds, so no provenance is +inferred from them; extraction needs a backend that reports origins. +Compiler extraction of splice origins is now real: compiler patch +`0004-splice-origins.patch` records one `splice` event from the reproduced GCC +16.2.0 frontend (the splice site plus the designated entity's kind, name and +declaration location), the worker trace accepts it with backward-compatible +handshakes, and the inspection snapshot exposes an `origins` array. Evidence +from a sealed session compiling `enum class State { Ready = 17 }; ... [:e:]`: + +``` +origins: [{"byteColumn": 31, "line": 4, "source": "input.cpp", + "targetByteColumn": 20, "targetKind": "declaration", + "targetLine": 1, "targetName": "Ready", "targetSource": "input.cpp"}] +``` + +`GccSupervisor.py` passed against the rebuilt frontend (`Live and offline GCC +sessions agree on 17/34 and 41/82, stale controls and cancellation`). The +registered test `Reflection.real_compiler_splice_origin_builds_a_provenance_chain` +feeds that exact recorded origin through `snapshot_from_splices` and asserts a +navigable, non-editable, complete chain (splice site then reflected +declaration) for `gcc:declaration:Ready@input.cpp:1:20`. The compiler reports a +start coordinate only, so ranges are zero-width until an end is available. +LSP adapters and index/rename/debugging integration remain open. `vbs test` +passed all 17 native suites; CMake passed the reflection and trace suites. + +## December 5 persistent index snapshot migration + +The symbol-index snapshot is now schema 2 with a canonical payload digest +(SHA-256 over the serialized payload without the digest itself). `restore` +classifies bytes before touching state: schema 1 is accepted and reported as +`migrated`, an unknown schema or backend is `incompatible`, malformed content or +a digest mismatch is `corrupt`, and over-limit bytes are `oversized`. Rejected +snapshots are quarantined and the index rebuilds. `restore_generation` persists +the upgraded snapshot (keeping `snapshot.prev.json`) and rewrites a legacy +`CURRENT` selector. Registered `vls_index_tests` grew from 20 to 24 cases: +`snapshot_schema_migration_is_reported_and_rewritten`, +`generation_restore_persists_the_migrated_schema`, +`digest_mismatch_is_quarantined_as_corruption` and +`schema_2_rejects_edited_records`. All 24 passed in VBS and CMake. The CMake +`vls_trace_tests` timeout was raised from 30s to 120s because the suite takes +about 25-30s in a Debug build (it passed VBS at ~27s); the full CMake run then +passed 18/18. + +## December 5 signature help from stock occurrence facts + +`include/vls/features/SignatureHelp.hpp` and +`src/features/SignatureHelp.cpp` parse the compiler-provided occurrence +signature into a label with parameter labels and nested-aware ranges, count the +active parameter at the cursor (bounded backward/forward scan that ignores +literals, comments and nested brackets), and decide whether a cursor lies in a +call's argument list (`in_call`). `EditorDiagnostics::signature_help` selects +the innermost call occurrence containing the cursor and `Server.cpp` +advertises `signatureHelpProvider` (`(`, `,`) and answers +`textDocument/signatureHelp`. `vls_feature_tests` grew from 13 to 27 cases. + +A real stdio session with the stock observer on `add(1, 2)`: +``` +at 'add(': activeParameter=0 (expected 0) signatures=1 + label: int add(int, int) + parameters: [{'label': [8, 11]}, {'label': [13, 16]}] +at 'add(1, ': activeParameter=1 (expected 1) signatures=1 +``` +All 18 native suites and all 18 CMake tests passed. + +## December 5 editor-driven module artifact production + +`tests/native/EditorModules.py` observed the +full editor path with the real compiler: after opening a module interface TU in a +compilation-database workspace, `moduleScan` provided `editor.cmi` and +`moduleArtifact` published a 64-character generation. This passed against the native +VBS-built server (`build/native/profiles/debug/out/bin/vls`) and against the installed +server after refreshing `build/install` from the comparison CMake build +(`editor modules: scan provided editor.cmi, artifact generation ...`). + +`vbs install` into that prefix currently fails with +`target 'vls_protocol' links unresolved imported target 'Void::Data' from dependency +'VoidLibrary'`, so the prefix was refreshed with `cmake --install build/bootstrap` +instead. The VBS native build and tests are unaffected. + +## December 5 index-backed cross-file rename coverage + +`include/vls/features/IndexNavigation.hpp` and +`src/features/IndexNavigation.cpp` merge a published symbol-index generation +into the navigation `FactSet`: unknown contexts join with the index's +completeness, each record's use and proven references become facts joined by +name and definition, duplicates never replace compiler-derived facts, and a +record whose source content identity is unknown stays non-editable so rename +refuses. `EditorDiagnostics::fact_set_locked` calls it with the current source +identities, so multi-file rename becomes ready when coverage is complete and a +transactional client is present. Registered `vls_feature_tests` grew from 6 to +13 cases, including `cross_file_rename_is_ready_from_index_data` (a real +`SymbolIndex` generation yields a two-file ready plan, while a non-transactional +client is refused), stale-content detection, incomplete-context blocking, +unknown-source refusal and cross-file reference joins. The stock occurrence +corpus still passed: `hover and definition selected string_view at Hash.hpp:59 +then byte_span at 65; module scan ready`. All 18 native suites and all 18 CMake +tests passed. + +## December 5 index-backed completion + +`textDocument/completion` is implemented for the bounded slice that the +current backend can prove: `include/vls/features/Completion.hpp`, +`src/features/Completion.cpp` and registered `vls_feature_tests` (label +`completion-hover`, 6 cases) cover identifier-prefix extraction, prefix +filtering with replacement ranges, label+kind deduplication, deterministic +ranking (types before functions before variables), bounded empty-prefix +listing and per-field limits. `EditorDiagnostics::completion` ranks the symbol +index and `Server.cpp` advertises `completionProvider` and answers +`textDocument/completion`. Every result is `isIncomplete` because the index +does not prove visibility: this is not compiler-native completion. A real stdio +session with the stock observer at `Void::Hash::fnv1a64(text)` returned +`fnv1a64` and `fnv1a64_update`. All 18 native suites and all 18 CMake tests +passed. + +## December 5 reflection adapters and debugging integration + +The reflection library now has LSP-shaped adapters: `hover(entity, expansion)` +returns Markdown explanation lines plus the provenance source links, and +`locations(provenance)` returns deduplicated, bounded navigation targets in +chain order. The live DAP `variables` projection consumes the worker's +`splice` origins through `snapshot_from_splices` and exposes each reflected +entity as a read-only entry with its declaration and splice coordinates. The +live worker fixture carries the real-shaped origin, and the registered DAP +test asserts `Ready` = `reflected Ready at input.cpp:1:20 (splice at +input.cpp:4:31)`. `vls_reflection_tests` passed 24 cases and `vls_live_tests` +7/7 in VBS and CMake. The LSP server path remains open because the private +worker runs only in `vls-dap`; `EditorDiagnostics` has no reflection data source +to serve yet. + +## December 5 registered C++ live-DAP typed projection + +The registered C++ DAP suite now asserts the typed projection over the live +adapter: `stackTrace` returns the `reflected_value` frame, `scopes` exposes its +handle, and `variables` contains `Result = 17` from the inspection snapshot. +The earlier failures were a dangling pointer in the test harness: `object_of` +returned a pointer into a temporary `wait_response` reply. Keeping each reply +in a local fixed it. Observed: `vls_live_tests` 7/7 passed in VBS. + +## December 5 private-compiler reproduction package + +`compiler-patches/gcc-16.2.0/configure.args` now records the exact 40 configure +options from the verified private build. `tools/prepare-private-gcc` validates +a GCC 16.2.0 source tree, classifies each patch as `unpatched`, +`already-applied` or `mismatch` with forward/reverse dry runs, prints the +reproduction recipe and either stops (`--check-only`) or copies the source, +applies the patches, configures and builds. + +Against `build/gcc-gate/gcc-16.2.0`, patch 0003 reports `already-applied`; 0001 +and 0002 report `mismatch`, so the set cannot be certified against that +already-built tree (overlapping patches or drift). A pristine GCC 16.2.0 source +is required to complete the validation, and the full build is a multi-hour +operation. The package is therefore implemented but not yet proven to reproduce +the existing compiler byte-for-byte. + +## December 5 index migrations and cross-context rename coverage + +`SymbolIndex::restore` classifies a saved snapshot and quarantines rejected +bytes instead of leaving them in place: a schema-9 snapshot and a corrupt file +were renamed to a `.quarantine--` sibling, the in-memory records were +cleared and a new generation was published; a compatible snapshot loads in +place and a missing one is reported separately. The index suite passed 15 cases. + +Navigation gained three cross-context cases: references from two complete +contexts are both returned and a transactional rename edits both files; an +incomplete second context refuses the rename and names it; a same-spelling +binding in another context is not renamed. The navigation suite passed 15 +cases. All 16 native targets and the comparison CMake suite (16/16) pass. + +## December 5 live DAP breakpoints and typed inspection + +`vls-dap --live` now maps `setBreakpoints` to the live session and projects +typed values from the inspection snapshot. The real DAP transcript test: + +```sh +python3 -B tests/native/LiveDap.py \ + --adapter "$PWD/build/native/profiles/debug/out/bin/vls-dap" \ + --worker "$PWD/build/native/profiles/debug/out/bin/vls_live_worker_fixture" +``` + +passed `stopped/typed inspection/breakpoints/step/stale rejection/continue, +pause refused`: the first stop exposed the projected `Result=17`; breakpoints +at lines 2 and 99 were verified, and the next stop carried +`hitBreakpointIds: [2]`; the previous stop's frame handle was then rejected as +stale. All 16 native targets and the comparison CMake suite (16/16) pass. + +## December 5 editor-driven module artifact preparation + +The semantic command grammar now accepts the module compilation flags +`-fmodules`, `-fmodules-ts` and `-fmodule-header` (plugins and forwarded +options remain refused). A synthetic compilation-database workspace opened a +real module interface and exercised the complete editor path: + +```sh +dev cpp-gcc -c python3 -B tests/native/EditorModules.py \ + --server "$PWD/build/native/profiles/debug/out/bin/vls" \ + --gcc-profile "$PWD/build/stock-occurrences/profile.json" +``` + +`EditorDiagnostics` submitted the P1689 scan through `ModuleWorkQueue`, decoded +a rule providing `editor.cmi`, then submitted artifact preparation at artifact +priority and published generation `53ba6589...`. Output: `editor modules: scan +provided editor.cmi, artifact generation 53ba6589...`. All 16 native test +targets and the comparison CMake suite (16/16) pass. + +## December 5 scan-driven module artifact generation + +The real-GCC module corpus decodes a P1689 scan through `ModuleWorkQueue`, then +uses the verified rule to prepare module artifacts through +`produce_module_artifacts_scheduled` at artifact priority: + +```sh +dev cpp-gcc -c python3 -B tests/corpus/modules/verify.py \ + --artifacts "$PWD/build/native/profiles/debug/out/bin/vls_module_artifact_fixture" +``` + +Observed: `scan: {'provides': ['corpus.cmi'], 'requires': [], 'generation': +'7be725904eaf6f5b27dae40b6ec4c3ca241cd27a991d3e80cbf1aa44e5c09764'}`. The +generation is a complete `ArtifactCache` publication of the CMI for the scanned +module. + +## December 5 real module scan through the editor work queue + +The module corpus ran a real GCC P1689 scan through `ModuleWorkQueue` and the +bounded Scheduler using `gcc_module_scan_work`, which executes the checked scan +command, reads the dependency file and verifies it with `decode_scan`: + +```sh +dev cpp-gcc -c python3 -B tests/corpus/modules/verify.py \ + --artifacts "$PWD/build/native/profiles/debug/out/bin/vls_module_artifact_fixture" +``` + +Observed `scan: {'provides': ['corpus.cmi'], 'requires': []}` alongside the +existing CMI production, supersession and importer checks. All 16 native test +targets pass. + +## December 5 module work admission in the editor scheduler + +```sh +dev cpp-gcc -c $VBS test --project "$PWD" --build-dir "$PWD/build/native" --profile debug --target vls_module_tests +``` + +`ModuleWorkQueue` was exercised against the real bounded Scheduler in the +registered module suite (five new cases): scans use the background pool while +artifact work completes independently during a saturated scan; a newer revision +cancels the running older one; cancelling a document stops both kinds; stale +revisions and empty keys are refused; terminal counts distinguish completion +from failure. `EditorDiagnostics` owns the queue and cancels per-document work +on edit/close and all work on shutdown. The full native suite (16 targets) and +the comparison CMake suite (16/16) pass. + +## December 5 live DAP control + +```sh +dev cpp-gcc -c $VBS test --project "$PWD" --build-dir "$PWD/build/native" --profile debug --target vls_live_tests +python3 -B tests/native/LiveDap.py \ + --adapter "$PWD/build/native/profiles/debug/out/bin/vls-dap" \ + --worker "$PWD/build/native/profiles/debug/out/bin/vls_live_worker_fixture" +``` + +`vls_live_tests` (CMake label `live-debug`) passed six cases: stepping through +stops with per-generation inspection, continue to completion, cancel at a stop, +refusal of movement without a stop, malformed worker output, and the notice +deadline. The DAP transcript test spawned `vls-dap --live`, initialized, +launched, configured, received `stopped`, read `threads`/`stackTrace`/`scopes`/ +`variables`, stepped with `next`, rejected the previous stop's frame handle as +stale, continued to `terminated`, and confirmed `pause` is refused. Output: +`live DAP passed: stopped/inspection/step/stale rejection/continue, pause refused`. +The full native suite (16 targets) and the comparison CMake suite (16/16) pass. + +## December 5 transactional rename application + +```sh +nvim --headless -u NONE -i NONE -l tests/native/NeovimRename.lua +python3 -B tests/native/VscodeClient.py \ + --server "$PWD/build/native/profiles/debug/out/bin/vls" \ + --adapter "$PWD/build/native/profiles/debug/out/bin/vls-dap" \ + --trace "$PWD/tests/debug/fixtures/integral-17.vls" +``` + +Neovim output: `Neovim rename passed: atomic apply, injected-failure rollback, +invalid range and read-only refusal`. The test applied a two-buffer rename, +then monkey-patched `nvim_buf_set_text` to fail on the second write and +asserted both buffers were restored byte-for-byte with their modified flags; +an out-of-range edit and a read-only buffer were also refused before mutation. + +VS Code output: `VS Code client passed: LSP status, replay session, timeline, +source, stale rejection and transactional rename`. The extension-host test +applied a two-document rename, then injected a document version change after +preparation and asserted the plan was refused with the other document +unchanged; an out-of-range edit was refused as well. + +## December 5 references and guarded rename + +```sh +dev cpp-gcc -c $VBS test --project "$PWD" --build-dir "$PWD/build/native" --profile debug --target vls_navigation_tests +dev cpp-gcc -c python3 -B tests/native/StockOccurrences.py \ + --server "$PWD/build/native/profiles/debug/out/bin/vls" \ + --gcc-profile "$PWD/build/stock-occurrences/profile.json" +``` + +`vls_navigation_tests` (CMake label `navigation-rename`) passed twelve cases: +unique binding resolution, same-spelling bindings distinguished by definition, +ambiguity not resolved by order, deduplicated references, incomplete-coverage +reporting, truncation, a ready cross-file rename with a transactional client, +and refusals for incomplete coverage, stale sources, non-editable origins, +multi-file without a transaction, invalid/generated/unchanged names and unknown +bindings. + +The real stdio corpus requested `textDocument/references`, +`textDocument/prepareRename` and `textDocument/rename` at the `fnv1a64` call. +Because the observer report is partial (system headers are not captured), all +three returned `-32803` with an explicit incomplete-coverage refusal instead of +a fabricated complete answer. Hover/definition and `workspace/symbol` still +succeeded. The full native suite (15 targets) and the comparison CMake suite +(15/15) pass. + +## December 5 context-aware symbol index + +```sh +dev cpp-gcc -c $VBS test --project "$PWD" --build-dir "$PWD/build/native" --profile debug --target vls_index_tests +dev cpp-gcc -c python3 -B tests/native/StockOccurrences.py \ + --server "$PWD/build/native/profiles/debug/out/bin/vls" \ + --gcc-profile "$PWD/build/stock-occurrences/profile.json" +``` + +`vls_index_tests` passed twelve cases: publication and query, same-spelling +distinct contexts, overlay shadowing and reconciliation, changed-source +incompleteness that keeps last-good records, dependency invalidation, context +removal, generation reader retention, persistence roundtrip, corrupt and +incompatible snapshot rejection, oversized snapshot rejection, deterministic +limit truncation and invalid-input rejection. The registered suite has the +CMake label `index`. + +`EditorDiagnostics` now publishes occurrence facts into the index after each +analysis and the server advertises `workspaceSymbolProvider`. The real stdio +corpus requested `workspace/symbol` for `fnv1a64` and reached the `Hash.hpp` +definition, while an unknown query returned an empty array; hover and definition +still selected the `string_view` overload then `byte_span` after the edit. The +full native suite (14 targets) and the comparison CMake suite (14/14) pass. + +## December 5 scheduler and module artifacts + +The scheduler-driven module artifact producer was verified with the real GCC +corpus: + +```sh +dev cpp-gcc -c python3 -B tests/corpus/modules/verify.py \ + --planner "$PWD/build/native/profiles/debug/out/bin/vls_module_scan_fixture" \ + --artifacts "$PWD/build/native/profiles/debug/out/bin/vls_module_artifact_fixture" +``` + +The artifact case published `corpus.cmi` through `ArtifactCache`, consumed the +published CMI with a real importer, rejected a truncated CMI, and then ran a +superseded build: the fixture held the unit after admission, submitted a newer +revision for the same key, and asserted the producer returned cancelled with no +published generation. A clean run afterwards published a new generation. The +same run passed the seven real planner corpus cases. Output excerpt: +`{'usable': True, 'truncated_rejected': True, 'superseded_published': False, +'clean_generation': 'b5b62d6e...'}`. + +The registered module suite also covers scheduler-driven production in +dependency order and a superseded production that publishes nothing (a +scheduler outcome of `cancelled` now overrides a stopped task's thrown error). + +```sh +dev cpp-gcc -c $VBS test --project "$PWD" --build-dir "$PWD/build/native" --profile debug --target vls_scheduler_tests +dev cpp-gcc -c $VBS test --project "$PWD" --build-dir "$PWD/build/native" --profile debug --target vls_module_tests +``` + +`vls_scheduler_tests` passed nine cases: work and metrics, foreground capacity +reserved under a saturated background pool, revision coalescing, cooperative +running cancellation, watchdog timeout, queue/oversize rejection, memory +serialization, exactly one terminal result across 100 superseded revisions, and +invalid-budget rejection. Repeated runs (40) passed and five runs of the +sanitized profile were clean after fixing a worker-construction order bug and a +drain race that could destroy a completion target while a worker still used it. +`vls_module_tests` added eight artifact cases: publish and find, failed +publication leaving nothing, content deduplication, reader retention across +eviction, retained-limit eviction, dependency-ordered production, producer +failure/cancellation publishing nothing, and unready-plan refusal. + +The scheduler now runs the `EditorDiagnostics` analysis jobs. The real stdio +corpus `tests/native/StockOccurrences.py` superseded a running revision and +asserted `scheduler.cancelled >= 1` in `analysisStatus` before the final +revision's hover and definition were served. The full native suite (13 +targets) and the comparison CMake suite (13/13) pass. + +## December 5 stock occurrence host integration + +The observer-enabled profile was prepared and the real Void translation unit was +exercised through a stdio LSP session: + +```sh +dev cpp-gcc -c python3 tools/prepare-gcc-profile \ + --observer "$PWD/build/stock-observer-014/occurrences.so" \ + --output "$PWD/build/stock-occurrences/profile.json" +dev cpp-gcc -c python3 -B tests/native/StockOccurrences.py \ + --server "$PWD/build/native/profiles/debug/out/bin/vls" \ + --gcc-profile "$PWD/build/stock-occurrences/profile.json" +``` + +Output: `stock occurrences: hover and definition selected string_view at +Hash.hpp:59 then byte_span at 65`. The session opened +`src/Documents/DocumentSnapshot.cpp`, waited for the selected TU analysis, and +checked that hover reports `fnv1a64` with its signature and canonical type, +that definition resolves to `Void/Core/Hash.hpp`, that the `string_view` +overload is selected, that the same query selects the `byte_span` overload at +line 65 after editing the argument, and that an unrelated position returns +`null`. The observer facts were `partial` as expected because immutable system +headers are outside the captured file set. + +The diagnostic suite grew to 38 cases, including nine occurrence decoder cases +for capture binding, negotiated UTF-16/UTF-8 conversion, wrong nonce, unknown +paths, mismatched bytes, duplicates, incomplete reports, withheld definitions +and malformed envelopes. All native and comparison test targets pass. + +## December 5 editor clients + +Both thin clients were exercised against the installed server and adapter +built in `build/native`. + +```sh +VLS_SERVER="$PWD/build/native/profiles/debug/out/bin/vls" \ +VLS_DAP="$PWD/build/native/profiles/debug/out/bin/vls-dap" \ +VLS_TRACE="$PWD/tests/debug/fixtures/integral-17.vls" \ +VLS_NVIM_DAP="$PWD/build/dap-evidence/nvim-dap" \ +nvim --headless -u NONE -i NONE -l tests/native/NeovimClient.lua + +python3 -B tests/native/VscodeClient.py \ + --server "$PWD/build/native/profiles/debug/out/bin/vls" \ + --adapter "$PWD/build/native/profiles/debug/out/bin/vls-dap" \ + --trace "$PWD/tests/debug/fixtures/integral-17.vls" +``` + +Neovim `0.12.6` and nvim-dap `cfa2d58f4537aca6ca83e2de1a0d9f1491121264` passed +with `Neovim client passed: LSP status, replay session, timeline, source and +stale rejection`. VS Code `1.147.0` (commit +`8a14f0cc1b08d531eb83255ea3764ae22aa932b5`) with Node `24.22.3` and npm `11.19.1` +passed in a disposable extension host with `VS Code client passed: LSP status, +replay session, timeline, source and stale rejection`. The VS Code test used +temporary user-data and extensions directories and invoked the application +binary directly because the Nix `code` launcher detaches from the terminal. + +## December 5 VoidLibrary main, JSON gate and stock observer + +VoidLibrary main `9cb86f8f978668215328ead51ee6f132552847c1` was prepared with +`tools/prepare-voidlibrary`. After `vbs deps resolve`, the native debug build +compiled 75 actions and all 12 test targets passed: + +```sh +dev cpp-gcc -c $VBS build --project "$PWD" --build-dir "$PWD/build/native" --profile debug +dev cpp-gcc -c $VBS test --project "$PWD" --build-dir "$PWD/build/native" --profile debug +``` + +`vls_json_capabilities` passed all eight cases, including +`rounded_fractional_id_cannot_change_lifecycle` and +`valid_number_outside_machine_range_is_still_json`. The earlier failures on +`e6745ac` were reported as [Void/Library#60](https://git.faumaray.com/Void/Library/issues/60) +and the issue was closed after this verification. The comparison CMake build +was reconfigured with `--fresh` against the same main and `ctest` passed all 12 +test targets. + +The stock GCC occurrence observer was built and verified with stock GCC 16.2.0 +and its matching plugin headers: + +```sh +dev cpp-gcc -c python3 tools/prepare-gcc-observer --output "$PWD/build/stock-observer-014/occurrences.so" +dev cpp-gcc -c python3 -B tests/corpus/frontend/verify-stock-observer.py --observer "$PWD/build/stock-observer-014/occurrences.so" +``` + +The prepared artifact reports plugin ABI 16.2.0, SHA-256 +`e4b19a4089fd69885b09887188bff26ae28d1b7f51eb87baf30910d8fffffe15`, and only +`libstdc++.so.6`, `libm.so.6`, `libgcc_s.so.1` and `libc.so.6`. Its two RUNPATH +entries are immutable compiler-runtime paths. `--inspect` accepts it and rejects +the planner's probe with its mutable project RUNPATH +`/home/faumaray/Projects/VoidLanguageServer/outputs/out/lib`. The verifier passed +same-line overloads and an overload edit, header definition and shift, macro +withholding, `#line` invalidation, a same-name qualifier, a declared-only call, +a template instantiation, UTF-8 BOM byte positions, a path with spaces, the +capacity quota, a compile error, recovery, malformed manifests, and a sealed +fixed-path run with 27 compiler runtime paths. + +## November 28 stock GCC diagnostics in the editor + +The Linux/Nix developer shell prepared a stock x86-64 GCC 16.2.0 profile with +48 immutable runtime and include mounts. Its unmodified `cc1plus` SHA-256 +begins with `984a888604a3`. The compiler profile is optional and local to the +launcher-selected workspace. The build still follows VoidLibrary main. An +upstream check returned `7d7d23ec0a6a55d4b30921432fa215b29a29e59b`, matching +the prepared source generation. + +The stdio corpus exercises the normal executable with an empty PATH, ordinary +LSP document notifications and asynchronous diagnostic notifications. A real +compilation database supplies the small workspace. The tests change a header +in memory, create and remove an optional header on disk, remove and restore +build metadata, and check a file timestamp observed by GCC. An error from a +header with a remapped line and filename remains available in analysis status +without attaching it to an inactive line in the editor. A client that omits +diagnostic version support receives notifications without a version field. + +In the native VBS workspace the client opens an edited `DocumentSnapshot.cpp`. +GCC diagnoses the missing member of `Void::Hash`. The notification covers +zero-based line 18, columns 33 through 40 exclusive. Fixing the source yields +an empty diagnostic list. A subsequent edit supersedes a running compiler +process. The transcript checks that the earlier version receives no result. +The initial TU needed ten isolated frontend passes to discover 605 workspace +lookup names. The recovered TU needed one pass. These are observations from the +development host. A positive test used a header with an on-disk timestamp in +January 2000. The worker preserves that timestamp and runs with a fixed UTC +timezone whose lookup stays inside the immutable toolchain. + +```sh +dev cpp-gcc -c tools/prepare-gcc-profile --output "$PWD/build/stock-editor/profile.json" +python3 -B tests/native/StockDiagnostics.py --server build/bootstrap/vls \ + --gcc-profile "$PWD/build/stock-editor/profile.json" --vbs-workspace "$PWD" +``` + +The two new catalog tests cover a missing parent becoming a directory and +metadata-only acquisition of existing files and directories. The resulting +suite has 26 cases. Both builds passed 264 of 266 C++ cases and the separate +registration executable. The native test command exited 1 and CTest exited 8. +Both failed only the rounded fractional JSON-RPC ID and valid out-of-range JSON +number cases. The eight preparation tests passed. The comparison executable +and the executable staged by VBS both passed the stdio corpus above, including +the real Void translation unit. The installed server also passed both position +encodings and resolved one command for `main.cpp` from 54 native and 76 +comparison database entries. The native build/test used VBS `6c225c2`; the +dependency-aware development CLI installed the executable under +`build/stock-editor/install`. The process logs in `build/stock-editor` include +`final-installed-editor.log`, `final-installed-passive.log`, +`final-native-test.log` and `final-comparison-test.log`. +The independent integration review, wider toolchain coverage and project-wide +diagnostics remain open. + +## November 28 source capture and immutable replay + +The native build and comparison build each enumerated 264 C++ cases. VBS test +exited 1 and CTest exited 8. Both passed 262 cases and the registration +executable. The two failures were the previously recorded exact JSON number +cases. This checkpoint added 14 source catalog and eight immutable recording +cases. The diagnostics executable passed 24 of 24, and the trace executable +passed 21 of 21. The freshly staged server's stdio test passed both position +encodings and selected the correct TU among 52 native and 74 comparison rows. + +The catalog binds an installed workspace grant and the editor store to each +capture. Tests used an actual file-access watch to verify zero payload reads +for a mismatched grant, a foreign census and a refused or desynchronized +overlay. Further cases cover an empty overlay, missing optional headers, +replacement of an identical-byte file, overlapping roots, retained bytes, +revocation during capture and bounded historical readers. A membership +witness lets a capture release unrelated editor buffers. + +Both builds' stock GCC fixtures passed the isolated source-view check with +the real catalog. Each staged the saved TU and three project headers through +the selected compiler context, then supplied an edited TU and Void header +from the document store. The real compiler diagnosed the edited inputs and +cleared the recovered source. The independent lookup-coverage and asynchronous +publication work remains necessary for production stdio diagnostics. + +Four real journals replayed offline with an empty PATH. The four-stop +recording yielded 17, 34, 22 and 44. The edited source yielded 41 and 82, +and the cancelled recording retained 41 with exit 125. The actual supervisor +test with the private GCC frontend also passed live control, replay, +cancellation, bounded diagnostic output and descendant cleanup. + +Full runs are in `build/native-evidence/catalog-recording-{ctest,native-test}.log`. +The two real source-view logs are `catalog-stock-{native,cmake}-corpus.log`. +The same directory contains `catalog-installed-test.log`, +`recording-real-offline.log` and `recording-live-supervisor.log`. + +## November 28 integrated build and stock compiler checks + +VoidBuildSystem and CMake each registered 242 C++ cases across ten suites and +ran the registration executable. Each passed 240 cases. The eight JSON number +cases had six passes and the two known failures for a rounded request ID and +valid JSON outside the numeric representation. VoidLibrary upstream main still +resolved to `7d7d23ec0a6a55d4b30921432fa215b29a29e59b`. + +| Suite | Registered C++ cases | +| --- | ---: | +| Unit, JSON numbers, stdio | 29, 8, 18 | +| Documents, workspace, build model | 37, 46, 18 | +| Providers, debugger trace | 42, 13 | +| GCC diagnostics, module planner | 10, 21 | + +The newly staged native executable negotiated UTF-8 and UTF-16 and detected +an edit that split the preceding replacement. It reported 49 VBS commands and +71 comparison commands from an empty working directory and PATH. Each provider +selected the sole owner of `src/main.cpp`. + +Both diagnostic fixture executables acquired a compiler lease on the real +`DocumentSnapshot.cpp` through native and compatibility metadata. The stock +GCC worker with isolated source inputs compiled the saved TU, observed both +edited overloads and located the bad edit. Its lookup of a positive host-only +`__has_include` control returned false inside the isolated process. + +```sh +dev cpp-gcc -c python3 -B tests/corpus/frontend/verify-stock-diagnostics.py \ + --fixture build/native-validation/profiles/debug/out/bin/vls_gcc_diagnostic_fixture \ + --comparison build/bootstrap/compile_commands.json --isolated-inputs +dev cpp-gcc -c python3 -B tests/corpus/modules/verify.py --cxx g++ \ + --planner "$PWD/build/native-validation/profiles/debug/out/bin/vls_module_scan_fixture" +``` + +The GCC module corpus checked 33 behaviors. Seven planner integration cases +covered baseline, edited and longer dependency orders, malformed data, incorrect +output identity, a pending header CMI and a failed compiler scan that produced +a rule. Logs are under `build/native-evidence`, including +`bound-source-{ctest,native-test}.log`, `stock-lease-view-{native,final}.log`, +`module-bridge-stock.log` and `semantic-current-installed-test.log`. + +## Stock diagnostics, module graph and installed contexts + +Both native `vbs build` and `cmake --build build/bootstrap` exited 0 on +the working tree with 210 registered C++ bodies. VBS test exited 1 and CTest +exited 8. Each ran eleven executables including registration. Only the +`vls_json_capabilities` suite failed, with six passing cases and the same two +precision/range failures. The rolling upstream main was rechecked at +`7d7d23ec0a6a55d4b30921432fa215b29a29e59b`. Inventories were independently +enumerated with each executable's `--list --no-color`. + +| Suite | Cases | +| --- | ---: | +| Unit, JSON capability, stdio subprocess | 29, 8, 18 | +| Documents, workspace, build model | 23, 29, 18 | +| Providers, debugger trace | 42, 13 | +| GCC diagnostics, module planner | 10, 20 | + +The native diagnostic fixture used unmodified dev-shell GCC 16.2.0 and the +selected VBS row for `src/Documents/DocumentSnapshot.cpp` from generation +`b7da5a9f204361f4`. The saved source, byte-span edit and restored source +compiled. Replacing `fnv1a64` with `missing` produced a compiler error at +line 19, columns [34,41), projected to LSP line 18, characters [33,40). +Distinct deprecated attributes in a copied Void header identified the +`string_view` and byte-span overloads. Removing them cleared the messages. +A real `#line` header preserved the error without attaching it to the inactive +line GCC named. This fixture supplies physical-location evidence for the +controlled edit. The stdio server does not yet publish compiler diagnostics. + +```sh +dev cpp-gcc -c python3 -B tests/corpus/frontend/verify-stock-diagnostics.py \ + --fixture build/native-validation/profiles/debug/out/bin/vls_gcc_diagnostic_fixture \ + --comparison build/bootstrap/compile_commands.json +``` + +The previous staged executable ran from an empty cwd with an empty PATH, +negotiated both encodings and reported all 41 native and 63 compatibility rows +that existed before adding the new targets. Two further installed transcripts +with 16 and 17 owners each agreed with the compact status response and its +truncation indicator. The C++ provider tests also verified the source language +of a checked compiler's actual operand, explicit `-x c` and a `.cpp` alias +pointing to a generated file with a different suffix. + +GCC prototype patch 0003 has SHA-256 +`46a66dcd255eec7872284e66db77fbb2db1add75536ea3f9a6a0ece024fe1da2`. +The combined private `cc1plus` has SHA-256 +`5823173025a7c58d042be2dd819a1f3437412811c1d4d3334b25cc31a3e586b2`. +Both evaluator and IDE harnesses exited 0. The repeated 19 language and +33 module checks using the reference driver and this ELF also exited 0. +The new BOM fixture distinguishes the terminal call name from a same-spelled +namespace qualifier three bytes earlier. + +## Live nested returns on the installed GCC package + +On November 27, the installed x86-64 Linux GCC 16.2.0 `cc1plus` with SHA-256 +`984a888604a33488e0fface3d1e4fd926ce11e45258244a120b9b71c002cbbeb` +ran the reflection fixture twice under GDB. The probe compiled a type object +from the package's matching public development headers and loaded it into GDB. +The compiler executable, arguments for evaluation and source assertions +required no instrumentation. The package retained the out-of-line call +evaluator symbol even though GDB could not resolve its source lines or locals. + +The standalone check exited 0. With the enum value 17, GDB held the compiler +at the inner and outer returns and read 17/34 for bias 0 and 22/44 for bias 5. +With the enum value 41 the corresponding pairs were 41/82 and 46/92. Each +compilation used one PID and exited successfully. The probe checks the callee +name, nesting, integer result and process identity. It does not classify an +unobserved call body, cache hit, constraint or splice. Other compiler builds +and architectures need their own validation. + +```sh +dev cpp-gcc -c python3 tests/corpus/frontend/verify-stock-gcc-gdb.py \ + --include-dir /nix/store/fs234b3nv0bv3jij5nf6jkpj5n575g8i-gmp-with-cxx-6.3.0-dev/include +``` + +The observed package exposes no public per-return evaluator callback. The +probe uses a GDB finish breakpoint and the compiler's matching tree types. +See [GCC 16.2 plugin events](https://github.com/gcc-mirror/gcc/blob/releases/gcc-16.2.0/gcc/plugin.def) +and [GDB finish breakpoints](https://sourceware.org/gdb/current/onlinedocs/gdb.html/Finish-Breakpoints-in-Python.html). + +## GCC evaluator prototype and build metadata on November 27 + +The reference and unmodified private GCC 16.2 frontend both passed 19 language +checks, eight tooling probes and 33 module/scanner checks. The private driver +used the reference compiler's ordered eleven header paths, explicit PIE and +the same standard predefines. Its macro set matched the reference. The +optional full compiler-tools build stopped in fixincludes on the absent +system /usr/include. Building the cc1plus target directly succeeded. + +Root applied compiler patch 0001 to the owned GCC release tree with zero +fuzz and rebuilt cc1plus. Patch SHA-256 was +`4b4ff5b664457dcdd1842ed63c8e8ff54896bb73ccc64c95ae8e4c173c5d52bf`. +The rebuilt executable SHA-256 was +`5780c2604fb49e70597a710c594627802f4c547f34335b74071496019e2f217f`. + +```sh +dev cpp-gcc -c python3 tests/corpus/frontend/verify-gcc-events.py \ + --cc1plus "$PWD/build/gcc-gate/compiler-build/gcc/cc1plus" +``` + +The independent root run exited 0. The compiler returned (17,34) and (22,44) +at biases 0 and 5. After editing the enumerator it returned (41,82) and (46,92). +The child held at the inner result, accepted a matching step, returned the +outer value and resumed. Separate children exited 125 on cancel and 126 on +control EOF or oversize input. Scalar width/sign, cache reuse, exception and +quota checks passed. Warm medians on 500 calls were 21.53 ms with hooks off +and 30.17 ms with 2,031 records. The pristine and instrumented builds used +different optimization flags, so the figures do not measure disabled-hook +overhead against pristine GCC. + +The provider reader passed its seven acquisition tests. The importer passed +17 tests. Passive import of actual database rows retained all 24 native and +47 CMake commands. With an explicitly checked compiler identity, all rows in +both generations classified. The native main translation unit retained three +reflection flags and the CMake row retained one. Native v1 lacks role and +per-command target metadata. The November 27 sanitizer profile linked both +libasan and libubsan, emitted `-fsanitize=address,undefined` and reproduced +the same two JSON capability failures as the debug foundation. + +## Integrated foundation and GCC tooling checks + +On November 27, the native debug build and optional CMake build listed the +same 106 C++ test bodies. Both passed 29 protocol/unit, 12 stdio process, +22 document and long-line, 17 workspace, 18 build-model and six of eight JSON +capability cases. Both registration executables passed. Native `vbs test` exited +1 and CTest exited 8. The two exact-number regressions below remain ordinary +failures. The install-capable development VBS staged the updated executable. +`python3 tests/native/InstalledServer.py build/native-evidence/install-reviewed/bin/vls` +verified its version, incremental edits, split-scalar diagnostics and lifecycle +in an empty directory and with an empty PATH. Dependency preparation passed +all eight cases with `python3 tests/native/Preparation.py -v`. + +The earlier independent review found a long-line slowdown. In paired GCC 16.2 +debug runs, the median 64 KiB near-end edit round trip fell from 7.71 ms to +2.86 ms. Release p95 fell from 0.50 ms to 0.33 ms. The three-run experiment +used eight edits per run. Release multiline p95 after the correction was +4.40 ms for 1 MiB and 34.27 ms for 8 MiB, using 20 edits per run. + +`dev cpp-gcc -c python3 tests/corpus/frontend/probe-gcc-tooling.py` exited 0 +on GCC 16.2.0. The compiler bound the original call to the integer overload at +line 6, the projected edit to the double overload at line 7, and the recovered +edit back to line 6. A malformed edit produced a SARIF error at line 11, +columns 20–27. Two independently built modules materialized enum values 17 +and 41. A failed concept reported six related locations. The instantiation dump +identified the nested consteval calls; a GDB probe stopped inside the actual +evaluator and resumed to completion. The prototype still needs event-time +variables and user-level control. + +GCC's release archive matched the published SHA-512 in +[the GCC release checksums](https://gcc.gnu.org/pub/gcc/releases/gcc-16.2.0/sha512.sum). +The four evaluator, constraint, template and reflection source files matched +tag commit `78d4ac73dd391005b895a6148cd9831e28e1208b` byte for byte. The +local compiler build uses an isolated directory under `build/gcc-gate`. + +## Native build, installation and reference corpus on November 27 + +Root used GCC 16.2 in the repository root. The native descriptor consumed the +immutable VoidLibrary main generation `3095596650a59c07588398f5ed5cf35bc990eb31f14abeecafd0b26aaaadf81c`, +revision `7d7d23ec0a6a55d4b30921432fa215b29a29e59b`. Preparation compared +119 selected files with their Git blobs. Root repeated +`python3 tests/native/Preparation.py -v`, which passed all seven tests. + +* The committed VBS 6c225c2 seed ran `vbs build --project "$PWD" --build-dir + "$PWD/build/native-validation" --profile debug --jobs 4`. The first clean + build exited 0 with 20 native dependency actions and 16 VLS actions. A failing + `cmake` executable headed PATH during every VLS action. The native suites + retained all 39 case names from the comparison build. Unit 22/22, subprocess + 9/9 and registration passed. JSON 6/8 passed. Full `vbs test` exited 1 and + comparison CTest exited 8 on the same two ordinary numeric regressions. +* The coordinated Protocol switch introduced seven encoding tests. Both builds + succeeded. The canonical unit suite grew to 29 cases, and full native and + comparison runs still failed only the two known JSON cases. The independent + package run passed its seven encoding tests under UBSan. +* The committed seed's native install omitted imported targets during graph + lowering and exited 1 on `Void::Data`. The local VBS development checkout + resolves dependencies for install. Its CLI uses ConsoleLogger, so the + isolated tool build added the existing `Void::Log` library to that executable + with a deferred CMake link command. Tool SHA-256 was + `703d8d7743865778fb9e16da631de4b552f498b851571632bc4c66250d5fc20c`. + VLS itself ran its native descriptor with CMake trapped. + `vbs install --project "$PWD" --build-dir "$PWD/build/native-development" + --profile debug --prefix "$PWD/build/native-evidence/install-dev" + --no-cmake-export` exited 0. From /tmp with an empty PATH, staged `bin/vls` + printed version 0.1.0 and completed its framed lifecycle with two correct + replies and empty stderr. Both VBS sources were read-only to this task. +* `dev cpp-gcc -c python3 tests/corpus/frontend/verify-gcc.py --void-include + build/bootstrap/_deps/voidlibrary-src/include` exited 0. All 19 reference + checks matched, including six expected errors and the imported reflection + splice. The pinned candidate was fetched and configured in build/frontend-gate. + +### Integrated document and workspace foundations + +Both builds linked the server and six test targets against the same upstream +revision. Root corrected the text-length check in LineIndex after a mismatch +regression failed in both builds. The incremental edit path updates that length +with the line offsets. Rerunning both full suites left the two JSON cases. +The native runner exited 1 and CTest exited 8. The registered C++ bodies were +29 unit, 17 document, 15 workspace, 11 subprocess and 8 JSON, totaling 80. +All 78 independent of the two JSON regressions passed. Registration independently +enumerated every suite and executed its named framing regression. + +Two additional focused subprocess cases passed with exit 0. The first replaces +`a` with an astral scalar and verifies the distinct UTF-8 and UTF-16 diagnostics +for a subsequent edit at column one. The second rejects a malformed late change, +a stale recovery and an out-of-range coordinate. Each transcript finishes with +only the initialize and shutdown responses. + +The native Release target also built with `--offline --profile release --target +vls --jobs 4`. On this machine, the real stdio edit-and-reply measurement ran +20 one-character replacements at different lines for each file size. At 1 MiB +the median was 4.03 ms, p95 4.45 ms and peak RSS 19,456 KiB. At 8 MiB they were +33.01 ms, 36.22 ms and 29,192 KiB. The command was `python3 +tests/performance/document_sync.py build/native-validation/profiles/release/out/bin/vls +--mib SIZE --samples 20`. These measurements include synchronization and one +JSON-RPC round trip. Compiler completion and navigation have separate budgets. + +### Pinned frontend fidelity experiment + +Root fetched candidate `562409c7942690d59ea470762515f88f24b16e23` into +`build/frontend-gate/source`. LLVM configured with GCC 16.2, assertions on, +Release with `-O1 -g0 -DNDEBUG`, X86, and one parallel link. Building the +external `clang` and `clang-resource-headers` targets completed 3,112 actions +and exited 0. The binary identified itself as Clang 21.0.0git at the exact SHA. + +`tests/corpus/frontend/probe-clang.py` used the GCC driver's target and system +include list, substituting the candidate's own compiler resource headers in +the builtin include slot. Six of ten compile checks passed. The cstddef +baseline, reflection/splice language control, constexpr-range expansion, plain +module provider/importer and the reflection module interface passed. GCC's +`` hid its declarations because the candidate lacked the required +`__cpp_impl_reflection` macro. Its module importer consequently lacked +`std::meta::identifier_of`. Both real Void enum header entry points stopped +inside Clang expression classification. The probe exited 1. GCC passed the +same Void header and module examples. Compiler-source repairs, alternate +backends, production IDE queries and debug instrumentation were outside this +experiment. The full report is retained under `build/frontend-gate/candidate-report.json`. + +Updated: 2026-11-27. The fetched bootstrap passes 37 of 39 cases after two +independent review findings were added to the suite. + +## Resumption evidence — 2026-11-27 + +Repository base ca04975d545efd4a891ee90edf22f130069bd191. Current branch +feat/implement-roadmap was created on explicit user instruction, preserving all +dirty/untracked work. No staging, commits, pushes or sibling edits in this run. + +The first ordinary configure/build succeeded but retained cached VoidLibrary9931c5f; +CTest exited8 with the previous6 JSON failures. A fresh configure was necessary to +refresh the dependency population stamps. The fetched and local source now both +resolve7d7d23ec0a6a55d4b30921432fa215b29a29e59b. StrictJson uses double for decimal +syntax and now has checked serialization; raw source was inspected because its +sibling graph was stale. No competing parser was added. + +Commands below ran in /home/faumaray/Projects/VoidLanguageServer: + +| Command | Observed result | +| --- | --- | +| `dev cpp-gcc -c cmake --fresh -S . -B build/bootstrap -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON` | Exit0; main7d7d23e fetched | +| `dev cpp-gcc -c cmake --build build/bootstrap --parallel 2` | Exit0 | +| `dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure` before CLI fix | Exit8; JSON6/6 pass, one process case fails on bare -- | +| Executable argument matrix via bounded Python subprocesses | Bare -- incorrectly exits1 after entering stdio; all other invalid modes exit2 | +| Same build and full CTest after src/main.cpp correction | Both exit0;4/4 entries,22 unit+6 JSON+9 subprocess cases pass | +| `dev cpp-gcc -c cmake -S . -B build/local -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVLS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidLibrary` | Exit0; explicit source override | +| `dev cpp-gcc -c cmake --build build/local --parallel 2` | Exit0 | +| `dev cpp-gcc -c ctest --test-dir build/local --output-on-failure` | Exit0; same4/4 entries and37 bodies | +| `dev cpp -c clang-format -i src/main.cpp` | Exit0; only the owned changed source formatted | +| Task linter on tasks/T-PLAN-002.md | Exit0 after setting READY contract status with blocked dispatch recorded separately | + +The pre-existing16-file uncommitted baseline was preserved under ignored +build/goal-baseline-20261127. No claim that the new foundation files are wired, +tested or independently reviewed. All existing37 test bodies remain enabled. +The user subsequently authorized explicit GPT-6.2 models at Max through the +generic runtime. Task contracts T-PLAN-002, T-RESEARCH-008 and T-REVIEW-003 +passed codex-tasklint. Dispatch accepted gpt-6.2-astra and reasoning_effort=max +for each. The spawn response exposed an agent ID and nickname only. + +The old sibling VBS binary and a relocated copy both aborted during profile +discovery. A driver compiled directly from the matching SDK sources returned +profiles successfully. The dirty sibling's CMake seed failed at link time on +ConsoleLogger constructor/destructor symbols. Its committed source at +6c225c2dff58b64fe8dbb0e5072f8e23f566efe5 configured and built successfully +under build/tools/vbs-6c225-bin, using GCC 16.2 and the tested VoidLibrary above. +Only committed build inputs and LICENSE were extracted from Git into the ignored +build directory. CMake served solely to bootstrap this build tool. + +From build/vbs-native-probe the resulting binary ran `vbs test --project . +--build-dir out-committed-seed --profile debug --jobs 2` with a failing cmake +executable at the front of PATH. Exit 0. VBS built the native VoidLibrary +dependency and compiled and linked the C++ probe, which parsed 1.25 as a double. +Its subsequent `vbs ide query` exited 0. The generated status described a +valid immutable generation with two real commands, for main.cpp and build.cpp. + +The five-module native framework probe built 20 dependency actions, then +compiled and ran a self-registering `VOID_TEST`. A direct list returned +`NativeRegistration.decimal`, and its filtered run executed one passing body. + +T-REVIEW-003 verified the CLI fix and the original 37 cases. Its stdin/stdout +probes reproduced precision loss and numeric range rejection, recorded in +REVIEW.md. After adding `rounded_fractional_id_cannot_change_lifecycle` and +`valid_number_outside_machine_range_is_still_json`, the fetched build succeeded +and full CTest exited 8. The JSON suite ran eight bodies with six passes and two +failures. Unit, process and registration entries passed. A focused rerun of just +the new bodies returned 1. The comparison build's earlier 37-case results above +precede these regressions. + +## Historical planning evidence — 2026-11-25 -## Planning evidence - `dev cpp-gcc -c g++ --version`: exit0, GCC16.2.0. - `dev cpp -c clang++ --version`: exit0, Clang23.1.3. - Syntax-only enum helper probe including Void/Detail/Enum.hpp: @@ -17,7 +967,7 @@ Updated: 2026-11-25. Builds and independent shell suites pass; final JSON accept directly. VBS graph lacked current source coverage. No reindex of secret-bearing sibling checkouts occurred. -## Implementation evidence +## Historical implementation evidence — 2026-11-25 All commands below ran in /home/faumaray/Projects/VoidLanguageServer unless stated. Root observed: diff --git a/docs/agent-workflow/tasks/T-CLIENT-NEOVIM-023.md b/docs/agent-workflow/tasks/T-CLIENT-NEOVIM-023.md new file mode 100644 index 0000000..7e60497 --- /dev/null +++ b/docs/agent-workflow/tasks/T-CLIENT-NEOVIM-023.md @@ -0,0 +1,126 @@ +# Thin Neovim LSP and replay-DAP client + +Task ID: T-CLIENT-NEOVIM-023 +Role: astra_implementer +Status: READY +Depends on: T-PLAN-EDITORS-022 (complete), T-DAP-TRANSCRIPTS-020, T-REVIEW-DAP-020 + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer on feat/implement-roadmap at +ca04975 plus uncommitted integration. Verified client tooling on this host: +Neovim `0.12.6` (LuaJIT 2.1) and the isolated nvim-dap checkout +`cfa2d58f4537aca6ca83e2de1a0d9f1491121264` under build/dap-evidence/nvim-dap. +Existing real journeys: tests/native/NeovimReplay.lua drives the installed +`vls-dap --replay` through a full nested-value session, and +tests/native/NeovimDiagnostics.lua drives the built-in LSP client through a real +unsaved edit, `voidLanguageServer/providerStatus` and stock GCC diagnostics. +No client package exists in the repository. + +## 2. Objective and deliverables +Add the thin Neovim client under clients/neovim/: native LSP setup for the +installed `vls`, passive provider/analysis status commands, and optional +nvim-dap configuration for an offline replay selected by the user. Deliver one +headless acceptance script that exercises the real installed executables. +Keep server semantics in C++; the Lua layer only starts processes, forwards +user actions and renders bounded replies. + +## 3. Scope and non-goals +In scope: plugin entry point, user commands, LSP client startup for a selected +workspace root, optional stock GCC profile argument, replay DAP adapter +registration, bounded timeline/frames/source views, stale-generation rejection +and clean shutdown. Non-goals: live debugging, semantic features implemented in +Lua, installing plugins into a user's configuration, distribution, and any +network fetch. Do not add a second language server or debug adapter. + +## 4. Files to inspect +Read docs/roadmap/23-neovim-client.md, tests/native/{NeovimReplay.lua, +NeovimDiagnostics.lua}, src/main.cpp (launcher options), src/Server.cpp +(capabilities, providerStatus, analysisStatus), src/debug/dap/{Main.cpp, +Projection.cpp}, src/debug/inspection/ReplaySession.cpp, README.md and +docs/agent-workflow/tasks/T-PLAN-EDITORS-022.md. Use nvim-dap's checked +documentation and `:help lsp` from Neovim 0.12.6. + +## 5. Write ownership and coordination +Write scope: clients/neovim/** and tests/native/NeovimClient.lua. No edits to +the server, DAP adapter, shared protocol headers, VBS/CMake registration, +existing tests, user configuration or the nvim-dap checkout. Root owns build +registration, docs and integration. The VS Code client is a disjoint package; +no shared TS/Lua code. + +## 6. Implementation approach +Use `vim.lsp.start` with an explicit executable, `--stdio`, the selected +workspace root and the optional `--gcc-profile`; do not shell out to discover +the server. Keep default LSP capabilities and let Neovim own buffers and +diagnostics. Commands: `:VlsStatus` requests `voidLanguageServer/providerStatus` +for the current document; `:VlsAnalysisStatus` requests +`voidLanguageServer/analysisStatus`; `:VlsReplay ` registers a +single nvim-dap adapter `vls-dap --replay ` and starts a launch only when +the user invokes it. Timeline/frames/source views use `vls/session`, +`vls/timeline`, `vls/frames` and standard `loadedSources`/`source` with the +current generation from the session reply. Reject replies whose sessionId or +generation differs from the subscribed generation. Close the session and drop +buffers on `terminated` or disconnect. + +## 7. Interfaces and data contracts +LSP: existing initialize/sync, `positionEncoding`, `workspaceFolders`, +`voidLanguageServer/providerStatus`, `voidLanguageServer/analysisStatus`. +Launcher: `vls --stdio --workspace-root ABS [--provider ...] [--gcc-profile ABS]`. +DAP: `vls-dap --replay ABSOLUTE_TRACE`; standard launch/configurationDone, +`stopped`, `stackTrace`, `scopes`, `variables`, `loadedSources`, `source`, +`continue`; custom `vls/session`, `vls/timeline`, `vls/frames`, `vls/seek`. +Every custom request carries schemaVersion, sessionId and generation; paging is +bounded by the server. Render only server-provided strings; never execute +recorded values. + +## 8. Dependencies and integration +Neovim 0.12.6 is already available; nvim-dap remains an optional test-only +dependency located by `VLS_NVIM_DAP`. The acceptance script takes +`VLS_SERVER`, `VLS_DAP`, `VLS_TRACE`, `VLS_NVIM_DAP` and, where diagnostics are +exercised, `VLS_GCC_PROFILE`. No dependency is installed by the test. Root +binds the script to an actual registered target only after the client exists. + +## 9. Edge cases, security and performance +Unavailable server/adapter, a workspace-local executable with the same name, +multi-root workspaces, omitted versus repeated settings, stale callbacks after +stop/seek/terminated, switching recordings, replaced buffers, binary captured +source and disconnect cleanup. Do not reuse or modify the user's editor +profile; the headless test must use `-u NONE -i NONE` and a temporary workspace. +Bound every wait and buffer render. Never open generated source as a workspace +file or clear third-party mappings/listeners. + +## 10. Acceptance criteria +1. Headless Neovim starts the installed server over stdio for a temporary + workspace and receives provider status for the current document. +2. A real unsaved edit still yields and clears stock GCC diagnostics when a + profile is supplied. +3. A recorded trace opens through nvim-dap, exposes the first stopped frame, + pages the timeline, reads captured source by reference, and follows continue + to the next recorded value. +4. A stale sessionId/generation reply is rejected without changing the view. +5. Terminating the session leaves no running server/adapter process and no + stale buffers or listeners. + +## 11. Verification commands and evidence +```sh +nvim --version +git -C build/dap-evidence/nvim-dap rev-parse HEAD +VLS_SERVER="$PWD/build/native/profiles/debug/out/bin/vls" \ +VLS_DAP="$PWD/build/native/profiles/debug/out/bin/vls-dap" \ +VLS_TRACE="$PWD/tests/debug/fixtures/integral-17.vls" \ +VLS_NVIM_DAP="$PWD/build/dap-evidence/nvim-dap" \ +nvim --headless -u NONE -i NONE -l tests/native/NeovimClient.lua +``` +Record exact versions, commands, exit statuses and the observed values. + +## 12. Constraints and stop conditions +No plugin installation, no user-config edits, no network, no commit or release. +Stop and return evidence if the installed Neovim or nvim-dap cannot expose a +required interface. + +## 13. Authorization and decisions +Full roadmap D-022, primary VBS D-025, GPT-6.2 Astra at Max D-027/029. Client +publishing and the project license remain deferred. + +## 14. Return format +T-CLIENT-NEOVIM-023 DONE/PARTIAL. Return paths, exact versions, test output, +supported commands and remaining limitations. diff --git a/docs/agent-workflow/tasks/T-CLIENT-VSCODE-022.md b/docs/agent-workflow/tasks/T-CLIENT-VSCODE-022.md new file mode 100644 index 0000000..292d695 --- /dev/null +++ b/docs/agent-workflow/tasks/T-CLIENT-VSCODE-022.md @@ -0,0 +1,119 @@ +# Thin VS Code LSP and replay-DAP extension + +Task ID: T-CLIENT-VSCODE-022 +Role: astra_implementer +Status: READY +Depends on: T-PLAN-EDITORS-022 (complete), T-DAP-TRANSCRIPTS-020, T-REVIEW-DAP-020 + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer on feat/implement-roadmap at +ca04975 plus uncommitted integration. Verified client tooling on this host: +VS Code `1.147.0` (commit +`8a14f0cc1b08d531eb83255ea3764ae22aa932b5`, x64), Node `v24.22.3` and npm +`11.19.1`. The LSP and replay-DAP services already run in real stdio sessions; +tests/native/DapReplay.py and tests/native/NeovimReplay.lua are the reference +journeys. No VS Code client package exists. + +## 2. Objective and deliverables +Add the thin VS Code extension under clients/vscode/: a language client that +launches the installed `vls --stdio` for the selected workspace, status +commands for `providerStatus`/`analysisStatus`, and a debug configuration that +launches `vls-dap --replay` on an absolute trace chosen by the user. Deliver a +disposable extension-host acceptance test that uses temporary user-data and +extensions directories. Keep all server semantics in C++. + +## 3. Scope and non-goals +In scope: package manifest, activation, language client startup and disposal, +status command output, debug adapter descriptor, a bounded replay tree view or +document provider for timeline/frames/source, stale-generation rejection and +clean shutdown. Non-goals: semantic features in TypeScript, live debugging, +marketplace publication, global installs, user-profile reuse, a second server, +or any network fetch during tests. No webview that executes recorded values. + +## 4. Files to inspect +Read docs/roadmap/22-vscode-client.md, src/main.cpp, src/Server.cpp, +src/debug/dap/{Main.cpp,Projection.cpp}, +src/debug/inspection/ReplaySession.cpp, tests/native/{DapReplay.py, +NeovimReplay.lua}, README.md and docs/agent-workflow/tasks/T-PLAN-EDITORS-022.md. +Consult the installed VS Code `vscode.d.ts`, `vscode-languageclient` and +`vscode-debugadapter` APIs for version 1.147.0. + +## 5. Write ownership and coordination +Write scope: clients/vscode/** and tests/native/VscodeClient.py. No edits to the +server, DAP adapter, shared protocol headers, VBS/CMake registration, existing +tests, user settings or installed extensions. Root owns build registration, +docs and integration. The Neovim client is a disjoint package; no shared code. + +## 6. Implementation approach +Activate on a C++ document or an explicit command. Resolve the server executable +from an explicit setting, never from the workspace `PATH`; start +`LanguageClient` with `serverOptions.command` and +`--stdio --workspace-root [--gcc-profile ]`. Register +commands `vls.providerStatus` and `vls.analysisStatus` that render bounded JSON +in an output channel. Register a `vls-replay` debug configuration taking an +absolute trace path and using `vls-dap --replay` as the executable adapter. +Render `vls/session`, `vls/timeline`, `vls/frames` and captured source in a +read-only tree/document provider keyed by sessionId and generation; drop replies +from an older generation. Dispose the client, adapter and views on +deactivation. + +## 7. Interfaces and data contracts +LSP: initialize/sync, `positionEncoding`, workspace folders, +`voidLanguageServer/providerStatus`, `voidLanguageServer/analysisStatus`. +Launcher: `vls --stdio --workspace-root ABS [--provider ...] [--gcc-profile ABS]`. +DAP: `vls-dap --replay ABSOLUTE_TRACE`; standard launch/configurationDone, +`stopped`, `stackTrace`, `scopes`, `variables`, `loadedSources`, `source`, +`continue`; custom `vls/session`, `vls/timeline`, `vls/frames`, `vls/seek`. +Requests carry schemaVersion, sessionId and generation; paging stays bounded by +the server. Do not reproduce server validation in TypeScript. + +## 8. Dependencies and integration +Node and npm are available; the extension test must reuse an installed VS Code +executable and a locally created fixture. Any npm dependency is declared in the +package manifest and fetched only by an explicit development step, never by the +test. The acceptance script takes `VLS_SERVER`, `VLS_DAP`, `VLS_TRACE` and an +optional `VLS_CODE`. It must pass `--user-data-dir`, `--extensions-dir` and +`--disable-extensions` for a disposable host, with a hard deadline. + +## 9. Edge cases, security and performance +Unavailable server/adapter, a workspace-local executable with the same name, +multi-root workspaces, omitted versus repeated settings, stale callbacks after +stop/seek/terminated, switching recordings, replaced documents, binary captured +source, extension deactivation and host shutdown. Never reuse a running editor +profile, write user settings, open the recorded source as a workspace file, or +execute recorded values. Bound waits, pages and rendered text. + +## 10. Acceptance criteria +1. The extension activates in a disposable extension host and starts the + installed server over stdio for a temporary workspace. +2. Status commands return provider and analysis state for the current document. +3. A recorded trace launches through the debug configuration, exposes the first + stopped frame, pages the timeline, reads captured source by reference, and + continues to the next recorded value. +4. A stale sessionId/generation reply is rejected without changing the view. +5. Deactivation and host shutdown leave no server/adapter process. + +## 11. Verification commands and evidence +```sh +code --version +node --version && npm --version +VLS_SERVER="$PWD/build/native/profiles/debug/out/bin/vls" \ +VLS_DAP="$PWD/build/native/profiles/debug/out/bin/vls-dap" \ +VLS_TRACE="$PWD/tests/debug/fixtures/integral-17.vls" \ +python3 -B tests/native/VscodeClient.py +``` +Record exact versions, commands, exit statuses, the extension-host log excerpt +and the observed values. + +## 12. Constraints and stop conditions +No marketplace publication, global installs, user-profile edits or network +during tests. Stop and return evidence if the installed VS Code cannot run a +disposable extension host on this host. + +## 13. Authorization and decisions +Full roadmap D-022, primary VBS D-025, GPT-6.2 Astra at Max D-027/029. Client +publishing and the project license remain deferred. + +## 14. Return format +T-CLIENT-VSCODE-022 DONE/PARTIAL. Return paths, exact versions, test output, +supported commands and remaining limitations. diff --git a/docs/agent-workflow/tasks/T-CORPUS-MODULES-011.md b/docs/agent-workflow/tasks/T-CORPUS-MODULES-011.md new file mode 100644 index 0000000..1452c65 --- /dev/null +++ b/docs/agent-workflow/tasks/T-CORPUS-MODULES-011.md @@ -0,0 +1,48 @@ +# Exercise the GCC 16 reference module topology + +Task ID: T-CORPUS-MODULES-011 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975, dirty files authorized. Primary native descriptor build.cpp, optional CMake verification, VoidLibrary main 7d7d23e. T-PLAN-006 verified VBS 6c225c2 selector/status/generations and actual compdb rows. Build/Model.hpp, Workspace/{Configuration,Trust}.hpp and Protocol/Json.hpp are implemented. Root owns build/test registration, CLI, session, docs and integration. No shared tree branch switches, Git mutations, sibling writes, child agents or independent user messages. + +## 2. Objective and deliverables +Extend the already-approved frontend reference corpus with actual GCC 16 module dependency scanner output, both partition kinds, implementation units, a header unit, global/private fragments and edited transitive inputs. Record real successes and compiler limitations. + +## 3. Scope and non-goals +Scope is bounded test corpus under D-028/D-030 and roadmap 08/11, independent of the provider review and GCC patches. No server semantics, source rewriting of real projects or fabricated module edges. Do not alter the existing corpus/reference results. + +## 4. Files to inspect +Read tests/corpus/frontend/{verify-gcc.py,probe-gcc-tooling.py,gate.cppm,importer.cpp}, docs/roadmap/08-frontend-feasibility.md and 11-cpp-modules.md, existing native GCC16 dev shell. For scanner flags verify installed GCC --help, exact release source in build/gcc-gate/gcc-16.2.0 if needed, and official GCC documentation. + +## 5. Write ownership and coordination +Write scope: tests/corpus/modules/ +Exclusively create the necessary .cpp/.cppm/.hpp fixtures and a small Python driver in this new subdirectory. Build private generated data in unique temp dirs; leave the VBS build, GCC prototype tree, other corpus, docs and build registration to root. + +## 6. Implementation or investigation approach +Use real GCC -std=c++26 -freflection -fmodules with source-owned compiler cache per generation and investigate its -fdeps-format=p1689r5/-fdeps-file flags. Check scanner edges against manually expected topology, header-unit path spelling vs lookup and target/flags. Compile and run consumers of a public partition and a private implementation path; assert a wrong old value cannot satisfy importer static_assert. Probe unsupported private module fragment explicitly with version + exit and correct diagnostic; never paper over GCC limits. Use fresh cache for transitive edits to prevent poisoning; keep old reader reusable. No shell commands from dependency metadata. + +## 7. Interfaces and data contracts +Driver uses actual gcc from --cxx or developer env, C locale, timeouts, bounded stderr. Emit a readable/JSON result distinguishing passed positive controls, expected negative controls and explicit missing backend capability; return failure for an unexpected outcome. Retain expected edges as fixtures; schema evidence cannot assume header units present in p1689 when not emitted. + +## 8. Dependencies and integration +Pre-existing GCC 19 source fidelity and 8 tooling probes already exercise basic module and reflected value. This is a corpus extension; root wires docs and production graph only once sources/worker ready. No production cache or graph changes. + +## 9. Edge cases security and performance +Test meaningful compile failures on visibility, missing provider, wrong context and at least one dependency change. Avoid system std headers where unnecessary for minimal reproducible topology. Private/module-cache artifacts never reuse source project CMI; pass/remove in test temp only. + +## 10. Acceptance criteria +Show real scanner output with normalized provides/requires per logical module for the supported set. Run reflection import under two controlled source/macro contexts and exercise the before/after result. Run real named targets for implementation unit/partitions and one header-unit import. Report exact gaps in compiler's private fragments, missing/system/header-unit edges, cycles or scans which cannot prove graph completeness. + +## 11. Verification commands and evidence +Run git status --short --branch, dev cpp-gcc -c g++ --version, dev cpp-gcc -c python3 tests/corpus/modules/verify.py, and Python compile checks without leaving artifacts in owned sources. Use isolated tmp cwd; report exact status and feature-specific output. + +## 12. Constraints and stop conditions +At two unsuccessful retries against an emitted format inspect actual compiler source/options and send root a changed hypothesis. Return an explicit unsupported result when source confirms. Do not invent missing native producer fields. + +## 13. Authorization and decisions +User approved GCC feasibility and local prototype. This small, independently testable reference-corpus extension follows the existing planner and feasibility review; it does not authorize semantic backends or compiler patches for this worker. GPT-6.2 Sol at Max. + +## 14. Return format +T-CORPUS-MODULES-011 DONE/PARTIAL/BLOCKED, paths, command, emitted graph, observed feature successes/gaps and integration consequence. diff --git a/docs/agent-workflow/tasks/T-DAP-TRANSCRIPTS-020.md b/docs/agent-workflow/tasks/T-DAP-TRANSCRIPTS-020.md new file mode 100644 index 0000000..ac55cee --- /dev/null +++ b/docs/agent-workflow/tasks/T-DAP-TRANSCRIPTS-020.md @@ -0,0 +1,48 @@ +# Exercise a real recorded compiler session through the DAP process + +Task ID: T-DAP-TRANSCRIPTS-020 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +The shared repo /home/faumaray/Projects/VoidLanguageServer is on feat/implement-roadmap, ca04975 plus local changes. T-PLAN-DAP-020 and the replay reader are in place. The root is implementing vls-dap; you own only tests. The independent preflight accepted initialization order and value mapping and required validation of UTF-8 before offering captured text. Three new, real, verified GCC journals exist in tests/debug/fixtures/{integral-17,integral-41,cancelled-41}.vls. Their exact source is the repository's tests/corpus/frontend/gcc-live.cpp, with Ready=41 in the latter two. + +## 2. Objective and deliverables +Write NEW tests/debug/DapReplayTests.cpp for the normal C++ inventory and NEW tests/native/DapReplay.py for interactive stdio scenarios using an actual vls-dap binary. Capture distinguishing behaviors that prove replay values, lifecycle ordering, generation-bound views and source ownership. Report test counts and an executable registration witness. Tests must preserve existing build and source files. + +## 3. Scope and non-goals +Recorded, offline GCC v1 integral evaluation only. These tests use real trace fixtures and benign temporary copies. Do not implement the adapter, live compiler, clients or build configuration. No custom journal parser or general source rewriter. + +## 4. Files to inspect +Read docs/agent-workflow/tasks/T-PREFLIGHT-DAP-020.md, experiments/frontend/gcc-worker/Trace.hpp, tests/{ProcessTests.cpp,TestExecutable.hpp}, tests/native/{StockDiagnostics.py,GccSupervisor.py} for existing process/framing patterns, plus the fixture paths above. Official Microsoft DAP overview and schema control standard responses. Root owns the CLI and future clients. + +## 5. Write ownership and coordination +Write scope: tests/debug/DapReplayTests.cpp, tests/native/DapReplay.py +Private outputs under build/test-dap-020 permitted. Shared root owns build.cpp, CMakeLists.txt, tests/CMakeLists.txt and tests/NativeRegistration.cpp. No other application/test changes or Git mutations. Tell root which files can be wired as soon as they compile. No other model or user contact. + +## 6. Implementation or investigation approach +Use registered Void::Testing C++ cases in suite DapReplay. For CMake root supplies VLS_DAP_EXECUTABLE as an absolute string compile definition and both builds use absolute __FILE__ to locate the three sibling fixtures. For native builds resolve vls-dap next to /proc/self/exe unless the compile definition is present. Reuse bounded Void::Process and Protocol framing. The Python corpus uses --adapter PATH and may take optional --fixtures PATH defaulting to tests/debug/fixtures. Use interactive framing with deadlines; test in an empty PATH with one adapter process per connection. Keep tests deterministic and small. + +## 7. Interfaces and data contracts +vls-dap --replay ABSOLUTE_TRACE. Send DAP seq=1,2,..., type=request, command and arguments. initialize(adapterID=vls) responds with configurationDone, terminate and loadedSources capabilities and emits initialized. launch may defer until configurationDone; configurationDone response precedes deferred launch response followed by stopped(threadId=1). Give launch no extra arguments; trace, if supplied, must name the same launcher-selected path. threads/stackTrace/scopes/variables/loadedSources/source/continue/terminate/disconnect are standard. Top frame at E6 is reflected_value over twice. A variable named Result shows 17, later 34; provisional state remains separately inspectable. Frames have no source and line/column=0 because original data has only logicalDeclaration. SourceReference is positive for valid text. Continue visits next observed integral value, even if no live STOP was recorded. Any unsupported next/stepBack is an explicit failure. vls/session returns schemaVersion=1,sessionId,generation,eventSequence,pauseKind,sourceAvailable,sourceByteLength,sourceReference when available, recording (outcome/exitCode/partial/corrupt), mode="replay". For vls/timeline and vls/frames copy schemaVersion/sessionId/generation and supply start/count (max 256). Body includes events or frames and total. Resumed events carry acknowledgedStop, acknowledgedAction. vls/frames includes lastLeave and captured frames with v1 fields. vls/seek accepts the same three identity fields and exactly one eventSequence or direction="previousValue" or "nextValue", responds with new identity before stopped. Old generation, frame and scope refs must fail even after seeking back to the same event. + +## 8. Dependencies and integration +The root will publish the binary path as soon as it links; interim checks can compile the test translation unit in isolation. The public DAP names above are frozen unless preflight requires a narrowly communicated change. Root owns both integrated builds and installation. + +## 9. Edge cases security and performance +Test correlations, configurationDone before/after launch, pending launch settled on disconnect, distinct DAP vs compiler ordinals, sourceReference/path mismatch cannot select disk, stale references, pagination under the public caps, partial/cancelled replay, invalid trace, unreachable state commands, no invented exited/step capabilities. Verify no file mutation for replay and no recompilation. Test a replaced/unlinked selected recording remains inspectable once opened. Use finite I/O deadlines, bounded logs and guaranteed child cleanup. No access to unrelated files. + +## 10. Acceptance criteria +1. C++ test runner lists nonzero DapReplay cases covering lifecycle, unavailable features and ordinary client controls; Python checks exact 17/34 plus 22/44 and edit 41/82 against real files. 2. Old handles fail across stop/seek ABA while captured bytes and sourceReference remain usable. 3. Historical E5 provisional result vs E8 committed lastLeave, E7 ack and E11 action appear only at the correct ordinals. 4. Cancelled recording presents a verified prefix and recorded exit 125, alone without live process. 5. Reports contain real executable evidence, expected outputs and any blocked cases. + +## 11. Verification commands and evidence +Run python3 -B tests/native/DapReplay.py --adapter "$PWD/build/bootstrap/vls-dap" once root confirms ready. C++: derive the GCC16 compile arguments from build/bootstrap/compile_commands.json for tests/debug/RecordingTests.cpp and replace only the TU/output into build/test-dap-020; use dev cpp-gcc -c. Root adds target vls_dap_tests, then run build/bootstrap/tests/vls_dap_tests --list --no-color and --no-color. Check dev cpp -c clang-format --dry-run --Werror tests/debug/DapReplayTests.cpp. Check Python syntax using ast.parse. No directory-wide format or build from your side. + +## 12. Constraints and stop conditions +Report early if the protocol contract is inconsistent with the verified v1 recordings or upstream DAP. Never weaken assertions to pass an implementation defect; send a distinguishing transcript. No pushes, commits, installs, toolchain changes or other agents. Preserve the shared worktree. + +## 13. Authorization and decisions +Full roadmap D-022, VBS D-025 and authorized GPT-6.2 Sol at Max D-027. The local compiler experiment D-030 has already produced all four recordings. The executing adapter uses stock libraries and reads the selected saved trace. + +## 14. Return format +T-DAP-TRANSCRIPTS-020 DONE/PARTIAL; changed files, cases/witness, commands and exit codes, observations, unmet contracts and release of ownership. Notify root of any confirmed protocol defect early. diff --git a/docs/agent-workflow/tasks/T-DIAGNOSTIC-SARIF-013.md b/docs/agent-workflow/tasks/T-DIAGNOSTIC-SARIF-013.md new file mode 100644 index 0000000..75f7cdc --- /dev/null +++ b/docs/agent-workflow/tasks/T-DIAGNOSTIC-SARIF-013.md @@ -0,0 +1,50 @@ +# Map stock GCC diagnostics onto the exact analyzed editor snapshots + +Task ID: T-DIAGNOSTIC-SARIF-013 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Shared VLS feat/implement-roadmap ca04975, D-028/D-030, Linux GCC16.2 with stock header/driver profile under evaluation. The planner compiled the genuine src/Documents/DocumentSnapshot.cpp with stock cc1plus, accepted both overload edits, and diagnosed a missing function at line 19, 1-based exclusive [34,41). Existing GCC SARIF 2.1 reports in build/gcc-gate/{constraint,queries}.sarif include one run, driver name/version, originalUriBaseIds.PWD, artifacts, regions, messages, relatedLocations, invocation.executionSuccessful and toolExecutionNotifications. GCC emits display columns even when columnKind is omitted; the Unicode witness display32/byte29/UTF16 unit26 appears in verify-gcc-ide.py. + +## 2. Objective and deliverables +Implement a reusable C++ adapter for the stock GCC diagnostics worker and immutable DocumentSnapshot mappings, with normalized typed diagnostic/related-location records and explicit unlocated/failed states. Root will supply actual captured SARIF files + admitted input snapshots and exercise the C++ adapter through a real compiler run. It is part of the planned editor diagnostic publication path. + +## 3. Scope and non-goals +Implement only decoding, source correlation, byte/position projection and typed outcome. No compiler launch, filesystem lookups, LSP transport/dispatch, worker scheduler or production backend choice. Reading a path supplied by SARIF is unnecessary and out of scope. Avoid a new JSON parser. + +## 4. Files to inspect +Inspect include/Void/LanguageServer/{Protocol/Json,Documents/{DocumentSnapshot,Position,Uri},Build/Model}.hpp, src/Documents/Position.cpp, tests/corpus/frontend/{gcc-queries.cpp,verify-gcc-ide.py}, live SARIF files above (actual GCC 16.2), docs/roadmap/13-diagnostics-recovery.md. Use real stock GCC to capture missing/empty/related fixtures where useful under private build/diagnostics-sarif-013. Source definitions for GCC display columns are in gcc/diagnostics/sarif-sink.cc in the local approved release, part is under gcc-gate. + +## 5. Write ownership and coordination +Write scope: include/vls/semantic/Diagnostics.hpp; src/semantic/Diagnostics.cpp; tests/semantic/DiagnosticTests.cpp +No shared build edits, protocol wire/JSON/source store edits, compiler or external source changes. Root owns integration, standalone real corpus and editorial docs. Other agents work in disjoint paths; no spawning or user messaging. + +## 6. Implementation or investigation approach +Decode a bounded one-run GCC16 SARIF result via Protocol::parse_json (accept only known schema/dialect/capabilities). Explicit invocation outcome (exited, code, truncation/completeness) comes from the caller. Exit 0 clean vs exit 1 with real source error is distinct from tool failure/truncation. A missing, malformed, unsupported or unmappable location remains explicit; never collapse incomplete or unsupported results into a clean empty batch. Match artifacts to caller-provided logical spellings/verified bases or explicit admitted URI table, including index indirection. No server cwd assumptions and no disk. Preserve messages/severity/rule, useful related source locations and truthful unlocated diagnostics. Capture code-quality data only, no automatic edits. + +## 7. Interfaces and data contracts +The caller binds an exact expected owning TU, its immutable lease and the same invocation/capture identity to the actual process status and diagnostic bytes. Only the unique matching analysisTarget in the attested run can admit an empty clear; some GCC absolute targets have no PWD, and empty successes may lack embedded contents. An individual source range needs a positively witnessed occurrence or a certified full analyzed input closure that excludes indistinguishable remaps. The active main source alone, matching bytes/snippets, and an identical text line in a header with a same-filename #line cannot prove origin. Default to unlocated until such proof exists. One unlocated related note does not invalidate an independently proven primary. Include both real-TU success confusion and same-line inert vs remapped text as distinguishing cases. +NEW namespace vls::semantic; report exact API early. Suggested inputs: completed process outcome + bounded bytes + a list of immutable retained DocumentSnapshots with verified SARIF artifact/base alias and provenance evidence from the snapshot worker; result either typed protocol/tool error or a complete batch with diagnostics and named mapping limitations. Each mapped location contains original URI and encoding-aware Docs::Range on that same snapshot. Validate end-exclusive bounds and 1-based coordinates. Ordinary ASCII yields exact positions. For tab, multibyte, combining, wide and BOM supports only known compiler tabstop/width policy and physically proven observations; if proof lacks a unique byte endpoint, name the gap. Do not assume OS wcwidth equals GCC. Use snapshot.offset_to_position for UTF8/16. A known #line/macro remapping/historical source must carry an explicit unmapped/witness contract; byte spelling alone does not prove physical source. Source text remains unchanged. + +## 8. Dependencies and integration +The semantic planner established stock real-TU diagnostics under D-028/030. Root and subsequent owners handle immutable worker snapshots, versioned invocation authorization, publication via AnalysisRevision/guards and editor notifications. This part can be independently verified before a production engine decision. Reply with frozen header once available so the root can build the actual GCC integration witness. + +## 9. Edge cases security and performance +Bound total bytes, depth, strings, locations, artifacts, results, related data and output memory. Bound normalization/lookup work across repeated huge locations without duplicate retained source-text copies. Detect conflicts between URI/base/index and duplicate artifact aliases, unknown origins, missing/extra compiler runs, oversized regions, partial side streams and multiple file/macro ambiguity. Do not open IO or trust embedded path/script properties. Empty clears only on a proven completed successful compilation. + +## 10. Acceptance criteria +The independent reviewer cleared the amended contract. In GCC 16.2 the SARIF emitter switches to raw byte columns if it cannot read the cited line; for a tab/astral/combining fixture the results were display [32,39), tabstop 4 [28,35), or byte [29,36). Require actual column-policy evidence or an unambiguous range. GCC may emit literal unescaped artifact names: do not merge a literal percent-20 filename with a literal space filename. Use the JSON integer variant for coordinates/indices. Handle errors before full evaluation or a missing main/include separately from a complete source-error batch; exit 1 with empty stderr is not clean. GCC can emit a valid related include entry with only startLine and no message, and an EOF end past the source remains unlocated. +Cases: captured GCC valid→empty, actual source-error→current located error, warning with severity/rule, related diagnostics, malformed/incomplete or inconsistent stream, failed launch/exit/signal/notifications, unbound/mismatching artifact cannot attach, both document encodings, CRLF/BOM/tab/astral/combining, excluded ambiguous ranges, invalid numeric/overflow or reversed positions without clamping. Include observed narrow GCC 16.2 SARIF files as evidence without requiring machine-specific paths. Include components with identical bytes but conflicting physical mapping. Test multiple artifacts/relative references and partial coverage separately from compiler-success verdict. + +## 11. Verification commands and evidence +Run dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only src/semantic/Diagnostics.cpp tests/semantic/DiagnosticTests.cpp. Root owns native+CMake test target registration. Use focused Void::Testing runner and private temp outputs if desired; provide exact case list/actual outcomes. Root's acceptance adds the real saved/edited Void TU SARIF through your adapter. + +## 12. Constraints and stop conditions +Stop for ambiguous dialect/source-map authority needing new API; retain unlocated reports if proof is unavailable. Track stock/GCC-specific behavior; never claim support for all vendors by accepting arbitrary JSON. No user decisions on licensing, production dependency or default compiler. + +## 13. Authorization and decisions +Full 27-roadmap implementation D-022, native build D-025, GPT-6.2 family Max D-027, scoped GCC evaluation D-028/030. No staging, commits, deployment or sibling changes. + +## 14. Return format +T-DIAGNOSTIC-SARIF-013 DONE/PARTIAL, public interface and files, source-mapping and clean-result invariants, real checks with counts/commands, remaining handoff. Return to root only. diff --git a/docs/agent-workflow/tasks/T-DOCS-003.md b/docs/agent-workflow/tasks/T-DOCS-003.md new file mode 100644 index 0000000..df7ddf4 --- /dev/null +++ b/docs/agent-workflow/tasks/T-DOCS-003.md @@ -0,0 +1,75 @@ +# Integrate the document model and verify overlay and position behavior + +Task ID: T-DOCS-003 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Repository /home/faumaray/Projects/VoidLanguageServer, branch feat/implement-roadmap, base ca04975. The Documents headers and implementations already exist untracked. User confirms no active writer and asks to continue them. Root preserved the original sixteen-file baseline in build/goal-baseline-20261127. This work implements roadmap 03 under R-006 and lays the document-side contract for 05/09. + +## 2. Objective and deliverables +Make the existing Documents namespace usable by the LSP session for real opens, edits, closes and overlay reads. Provide tested immutable snapshot identities and consistent change/recovery semantics. Root integrates your library and tests with the server and native build. + +## 3. Scope and non-goals +Own the document engine, URI/position boundaries and its focused tests. Keep source content immutable to callers. Protocol framing, LSP JSON decoding, dependency preparation, configuration, semantic workers, VBS build descriptions and shared build/revision model are separate. + +## 4. Files to inspect +Inspect include/Void/LanguageServer/Documents/{Position,Uri,DocumentSnapshot,DocumentStore}.hpp, src/Documents/{Position,Uri,DocumentSnapshot,DocumentStore}.cpp and docs/roadmap/03-documents-positions.md. Consult roadmap 05 and 10 for snapshot stability; docs/roadmap/ARCHITECTURE.md is the context. VoidLibrary headers live in build/bootstrap/_deps/voidlibrary-src/include/Void/{System,Unicode,Crypto,Text}. + +## 5. Write ownership and coordination +Write scope: include/Void/LanguageServer/Documents; src/Documents; tests/documents +The existing files are the baseline. New tests are confined to tests/documents/DocumentTests.cpp. Do not edit shared build files, CLI/server, TestSupport.hpp, sibling trees or docs. Root wires targets and resolves inter-component ownership. No Git mutations. + +## 6. Implementation or investigation approach +Implement position clamping for character offsets beyond line end per LSP 3.17 (retain rejection inside UTF-8 scalars/UTF-16 surrogate pairs). Make invalid line, EOF and newline boundaries deliberate and safe. Ensure valid file/virtual URI identities and aliases, without conflating unrelated paths or losing the URI used to close an open overlay. Keep apply_changes transactional across a batch and monotonic across failed/recovered versions. A newer full replacement or close/reopen recovers desync. Bound overlay growth independently of single JSON frame limits. File reads outside the store lock recheck overlay, desync, and encoding before returning success OR error. Avoid quadratic full reindexes per edit when feasible and never allocate unbounded aggregate batches. Use the reviewed planner/preflight decisions for limits and identity policy. + +## 7. Interfaces and data contracts +Retain existing Documents::DocumentStore::open, apply_changes, close, snapshot, resolve_content; const shared_ptr snapshots carry text, content identity, line map, version and revision. Any additional needed method to mark malformed known-document notifications desynchronized should accept an explicit error and version where available and notify root of the exact signature. Use C++26 expected with typed document errors. Make public line helpers safe on untrusted indices or move unchecked helpers private. + +## 8. Dependencies and integration +Read-only T-PLAN-002 and fresh preflight freeze the API. Other workers own build/test wiring, protocol and workspace. Keep your suite self-registering (VOID_TEST) so both native and CMake harnesses can link the same bodies. Root owns server notification behavior and provider integration. Report the exact native source/module list and test names. + +## 9. Edge cases security and performance +Exercise line-ending forms, astral scalars, combining marks, truncated UTF-8, nonexistent files, encoded separators/NUL, multi-edit ordering, old snapshot lifetime, stale versions, aliases and a newly-opened overlay while resolving disk. Passive content resolution never writes disk. Any deterministic race test should use an explicit bounded seam or observable synchronization, never flaky sleeps. Honor the roadmap limits for bounded text, errors and cancellation. Use a current upstream public SHA-256 API if the reviewed contract needs it. + +## 10. Acceptance criteria +1. Both encodings round-trip valid positions, clamp oversized character values and detect invalid scalar/newline splits. +2. Sequential edits use preceding element state, failure publishes no partial text and preserves a clear desync barrier. Recovery and close/reopen create fresh identities while prior snapshots remain consistent. +3. Overlay precedence, including a raced failure/success disk read and URI alias behavior, is verified. Bounded disk/overlay limits have tested outcomes. +4. Focused tests exercise actual APIs, remain discoverable under native registration and pass. Report large-file/edit measurement and any residual issue. + +## 11. Verification commands and evidence +From repository root, use dev cpp-gcc -c g++ -std=c++26 -freflection with -Iinclude and -Ibuild/bootstrap/_deps/voidlibrary-src/include for an isolated -fsyntax-only check. A compiled Void::Testing runner and real native archive already exist under build/vbs-framework-probe; discover the exact archives via its link action or the root-owned native/CMake build. Run the dedicated test binary in your own ignored build/docs-check if root wiring is not yet available. All repo build scripts are reserved. Use dev cpp -c clang-format on exact owned C++ paths. Include actual execution commands and counts. + +## 12. Constraints and stop conditions +Stop if continued work requires changing the agreed shared revision schema, unowned files or dependency APIs. Return proposed changes to root. After two failed repairs for the same contract return reproduction, attempts and current diff. No broad sibling search, sensitive files, staging, commits or branch changes. + +## 13. Authorization and decisions +D-022, D-024 through D-027 authorize the full roadmap, work on existing files and explicit GPT-6.2 Sol Max. Implement after fresh preflight and root dispatch. Follow project agent instructions and the reviewed contracts. Other agents share the checkout. + +## 14. Return format +Return T-DOCS-003 DONE/PARTIAL/BLOCKED, changed files, public signatures, edge-case outcomes, test counts and commands, performance measurement, unverified risks and exact integration points. No children or independent user messages. + +T-PLAN-002 clarification: distinguish lexical client URI/open incarnation and +physical lookup. Keep the original client URI available after symlink retarget, +and treat two live overlays for the same physical path as ambiguous for that +lookup. Disk snapshots have explicit origin and no client version. Track the +highest observed change version independently of last applied so a failed v12 +cannot recover from v10. Newer full text may be followed by valid ranged edits +in the same notification. Recheck path generation including open/close ABA after +disk I/O, bounded retry or typed stale. Suggested session defaults are 16 MiB +per document, 128 MiB snapshot/index admission, 4096 open documents and 4096 +changes per notification. Track snapshot lifetime while references remain. +Use LSP signed-32-bit versions and positions up to 2^31-1. + +Preflight correction: reserve lightweight unavailable-open/desynchronization +state independently of document text allocation. When a valid didOpen exceeds +budget, the client still owns its content. resolve_content must report unready +and may never substitute disk. Define a bounded fail-closed state if even the +unavailable-open marker limit is reached. Reject stale events without allocating +or copying an entire text/index to set a desync barrier. + +For disk inputs distinguish stable origin/content and a path/overlay epoch from +a newly allocated snapshot's in-process sequence. Re-reading an unchanged file +must not by itself invalidate an analysis revision. Report the read/identity API +to root for the shared context model. diff --git a/docs/agent-workflow/tasks/T-DOCS-PERF-006.md b/docs/agent-workflow/tasks/T-DOCS-PERF-006.md new file mode 100644 index 0000000..ee00023 --- /dev/null +++ b/docs/agent-workflow/tasks/T-DOCS-PERF-006.md @@ -0,0 +1,48 @@ +# Remove repeated prefix decoding for long-line incremental edits + +Task ID: T-DOCS-PERF-006 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Shared checkout /home/faumaray/Projects/VoidLanguageServer on feat/implement-roadmap at ca04975. The Documents store passed 17 focused cases after the text_size_ repair. The fresh integrated reviewer T-REVIEW-005 observed a P2: eight single-character edits near the end of one 64 KiB ASCII line took 42.36 ms versus 3.09 ms near the beginning in the native debug build. Root separately owns its torn-read and envelope corrections. + +## 2. Objective and deliverables +Fix the long-line position conversion on actual document edit paths while preserving Unicode/CRLF and memory admission. Add a repeatable long-line option to the existing benchmark and new narrow correctness coverage for edits that introduce/remove Unicode. + +## 3. Scope and non-goals +Only the position index and performance evidence. Leave store, disk, session, preparation, existing document tests and all build configurations to root. The current scope is a small evidence-driven regression fix, validated by the existing planner and fresh reviewer. + +## 4. Files to inspect +Inspect include/Void/LanguageServer/Documents/Position.hpp, src/Documents/Position.cpp, src/Documents/DocumentStore.cpp especially apply_changes/apply_replacement/line admission, tests/documents/DocumentTests.cpp and tests/performance/document_sync.py. The native debug and release tools are under build/native-validation/profiles/{debug,release}/out/bin. + +## 5. Write ownership and coordination +Write scope: include/Void/LanguageServer/Documents/Position.hpp; src/Documents/Position.cpp; tests/documents/LongLineTests.cpp; tests/performance/document_sync.py +These four paths are exclusive to you. New tests go into LongLineTests.cpp. Root and other workers share all other paths. No branch changes, sibling edits, staging, or common native build/metadata writes. + +## 6. Implementation or investigation approach +Choose a measured ASCII fast path or bounded sparse checkpoints that avoid decoding from line start for routine ASCII edits. Share decoded traversal between two endpoints on the same line. Preserve direct public checks, per-session encoding, line clamping, size/offset validation and atomic edits. Keep every new allocation charged under the existing storage contract; prefer a constant-space approach where possible. Include a mixed-ASCII/Unicode long-line case. Optimize the release code used by DocumentStore. Do not change quotas or skip validation to improve the benchmark. + +## 7. Interfaces and data contracts +Keep existing public LineIndex APIs usable. The checked same-size index contract applies to original snapshot text; changed-size mismatches return an error. apply_replacement gets old text and already validated start/end bytes, plus the replacement and max-lines allowance. An edit creating/deleting CRLF or non-BMP sequences must update any new metadata correctly. New tests use native VOID_TEST(LongLines,...). Retain tests/performance/document_sync.py's original size/samples behavior. + +## 8. Dependencies and integration +Root integrates new tests into both builds after handoff. Return the --list names and your independent run using an isolated compiler invocation and the real native or comparison Void::Testing libraries. For benchmark use a freshly linked binary with the changed position code under your own build/doc-perf path or coordinate with root for the shared binary once source changes are ready. + +## 9. Edge cases security and performance +Keep algorithmic bounds explicit and avoid mutable data races in shared immutable snapshots. Verify UTF-16 split-surrogate, UTF-8 split-scalar, invalid/truncated UTF-8 and integer upper boundaries. Do not introduce full-document work per small edit solely to maintain an optimization. Bounds still cover exceptionally long single lines, repeated edits and retained snapshots. + +## 10. Acceptance criteria +1. Real nonempty tests for long ASCII endpoints, mixed Unicode positions, and transitions from ASCII to Unicode and back through ranges/full replacements. Existing 17 cases remain meaningful. 2. Repeat the 64 KiB single-line near-start and near-end workloads, report before/after counts, timings/build profile. 3. Preserve actual behavior under original multiline 1/8 MiB benchmark and original public API. 4. No unaccounted memory or per-request mutable shared caches. + +## 11. Verification commands and evidence +Run git status --short --branch, read actual source and scoped graph coverage. Use dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only src/Documents/Position.cpp tests/documents/LongLineTests.cpp. Link and execute real tests in build/doc-perf using present libraries; root will register both builds. Run dev cpp -c clang-format --dry-run --Werror on your three C++ paths and python3 tests/performance/document_sync.py --help. + +## 12. Constraints and stop conditions +Stop and notify root before incompatible store/storage changes or after two unsuccessful repair attempts with the same hypothesis. Keep original failing/performance witness visible. Do not rewrite generic test framework or performance targets. + +## 13. Authorization and decisions +The user explicitly reiterated all plans and Max on all agents, and already selected GPT-6.2 fallback at Max after escalation. This bounded correction uses the approved Sol role on that family. No external side effects, no children or user messages. + +## 14. Return format +T-DOCS-PERF-006 DONE/PARTIAL/BLOCKED, exact paths, algorithm/public invariants, benchmark commands/outputs, test registration/count/results, remaining gaps and root wiring required. diff --git a/docs/agent-workflow/tasks/T-FIX-DIAGNOSTIC-COLUMNS-013.md b/docs/agent-workflow/tasks/T-FIX-DIAGNOSTIC-COLUMNS-013.md new file mode 100644 index 0000000..c494ae4 --- /dev/null +++ b/docs/agent-workflow/tasks/T-FIX-DIAGNOSTIC-COLUMNS-013.md @@ -0,0 +1,49 @@ +# Correct ambiguous GCC display columns at zero-width characters + +Task ID: T-FIX-DIAGNOSTIC-COLUMNS-013 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +The shared repository /home/faumaray/Projects/VoidLanguageServer is on feat/implement-roadmap, ca04975 with local work. Existing stock GCC 16.2 diagnostics ship through stdio. The independent reviewer reproduced a seven-bit letter followed by U+0301 or U+200D giving the same display endpoint on both sides of the subsequent scalar. Reader::position currently stops at the first matching display column. An error on the full identifier highlights only its first letter. The 26 diagnostics and source-catalog tests presently pass. + +## 2. Objective and deliverables +Fix the incorrect range at this boundary in the existing decoder, supply distinguishing regressions and verify the actual source witness. Continue to mark a diagnostic unlocated when its origin or range cannot be proved. + +## 3. Scope and non-goals +The assignment covers source-column admission inside the SARIF decoder. Preserve the public API, existing units, limits, UTF-8/UTF-16 conversion, BOM and tab rules. The root owns DAP and build registration. Leave source capture, worker execution, module graph, driver configuration and unrelated findings to their owners. + +## 4. Files to inspect +Read src/semantic/Diagnostics.cpp, include/vls/semantic/Diagnostics.hpp, tests/semantic/DiagnosticTests.cpp, tests/semantic/GccDiagnosticFixture.cpp, docs/agent-workflow/tasks/T-DIAGNOSTIC-SARIF-013.md and the reviewer's benign inputs under build/review-semantic-013. Verify which existing display policies actually support non-ASCII. Confirm limits from the function itself. + +## 5. Write ownership and coordination +Write scope: src/semantic/Diagnostics.cpp, tests/semantic/DiagnosticTests.cpp +Use build/fix-diagnostic-columns-013 for private outputs. Root owns every build file and the normal build directories and will run both integrated suites. The reviewer remains a separate read-only owner. Do not edit other files or change branches. + +## 6. Implementation or investigation approach +Reproduce before editing. An actual source spelling is int f(){return é;} with e followed by U+0301. GCC reports 1-based exclusive [16,17) at line 1. The current adapter produces UTF-16 [15,16), hiding the trailing scalar. Require a unique end and start in the supported coordinate convention. When unable to characterize a following non-ASCII scalar safely under the display policy, withhold the location. Keep a proven byte boundary usable under utf8_bytes. Avoid adding a competing Unicode width table if a small conservative proof suffices. Preserve valid ASCII cases and whichever uniquely provable non-ASCII prefixes are covered by the original contract. + +## 7. Interfaces and data contracts +The independent review also demonstrated that an artifact table entry declaring a conflicting self-index can authorize an empty clear. In the same two owned files, require any present artifact location index to be its actual table position using the exact integer variant. Exercise out-of-range, wrong-type and conflicting index cases against the valid position. +decode_gcc_diagnostics maps DiagnosticJob + DiagnosticOutput into DiagnosticBatch. A gap uses LocationGap::ambiguous_column, retains the compiler message and prevents a false complete clear. Both endpoints and the original immutable source snapshot matter. Preserve policy distinction between ascii_consensus, gcc_display and utf8_bytes; keep bounds in the reader's work budget. + +## 8. Dependencies and integration +Based on T-REVIEW-SEMANTIC-013's November 28 independent evidence. No compiler modification or upstream dependency required. Notify root when independent object checks and patches are ready. Root will perform integrated build and re-review. + +## 9. Edge cases security and performance +Check a zero-width codepoint exactly after the candidate boundary, at the beginning of a line, multiple zero-width scalars, and a normal ASCII control. Preserve bounds on maliciously long lines and repeated diagnostics. Do not introduce file reads while decoding or attach guessed locations. + +## 10. Acceptance criteria +1. The combining and joiner witnesses never return the incorrect partial-token highlight. 2. A validated UTF-8 byte report and an ordinary ASCII token still map correctly in the negotiated encoding. 3. A partial result retains its message and distinguishes unavailable columns from a valid empty report. 4. All previous body registrations are preserved. + +## 11. Verification commands and evidence +Use dev cpp-gcc -c with the compile definitions and include directories from build/bootstrap/compile_commands.json. Compile the two owned files into the private directory; link a dedicated test runner using the existing library and test main as appropriate, or ask root for the normal build at handoff. Run the focused Void::Testing suite with --no-color and the existing GccDiagnosticFixture on the reviewer's recorded SARIF if practical. Run dev cpp -c clang-format --dry-run --Werror on the two owned files. Report actual commands and outcomes, and the new test count. + +## 12. Constraints and stop conditions +If source representation or parser differences invalidate the witness, report exact evidence. No Git mutation, sibling edits, shared builds, extra models, further workers or messages to the user. Stay within the two owned paths. + +## 13. Authorization and decisions +D-022 authorizes all roadmap development, D-025 native integration, D-027 GPT-6.2 Sol at Max. This scoped correctness fix fits the existing preflight contract. + +## 14. Return format +T-FIX-DIAGNOSTIC-COLUMNS-013 DONE/PARTIAL with owned files, direct test results, prior/fixed outputs, case count and release of ownership. Send an early implementation-ready notice to root. diff --git a/docs/agent-workflow/tasks/T-GCC-EVALUATOR-017.md b/docs/agent-workflow/tasks/T-GCC-EVALUATOR-017.md new file mode 100644 index 0000000..94f03d2 --- /dev/null +++ b/docs/agent-workflow/tasks/T-GCC-EVALUATOR-017.md @@ -0,0 +1,48 @@ +# Capture and stop on real GCC 16.2 integral evaluator results + +Task ID: T-GCC-EVALUATOR-017 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975. No other compiler patch owner. User D-030 approved this local prototype. GCC 16.2 official archive c51c30ca7422d0cbecf504b2e0f33c3aca31e0f90a76b65217f465163fa6fa17b3f5de39e145c47e5bab90ac0ce7fff3b03c8d553ae36e01faaea5a50f8648d1 matches release tag 78d4ac73dd391005b895a6148cd9831e28e1208b. Private cc1plus built, matched host predefined macros/ordered libstdc++ via reference-cxx and passed 19 reference, 8 tooling and 33 module scans. Preflight T-PREFLIGHT-GCC-008 cleared the ordinary integral evaluator slice with amendments below. + +## 2. Objective and deliverables +Implement the first versioned patch to real GCC internals and a direct bounded runtime fixture. Produce actual event-time integer values, nested bodies and cooperative stops in an isolated cc1plus process. Send the patch/application instructions early so root can build while you finalize the harness. + +## 3. Scope and non-goals +Only compiler hooks for ordinary integral consteval/constexpr returns, metadata/handshake, stops and direct test harness. No AST lookup/diagnostics relocation, VLS client/worker launch implementation, production registration or changes to installed compilers. Constraints/reflection semantic events are a later slice. + +## 4. Files to inspect +Read docs/agent-workflow/tasks/{T-PLAN-GCC-008,T-PREFLIGHT-GCC-008}.md, tests/corpus/frontend/gcc-live.cpp, exact build/gcc-gate/gcc-16.2.0/gcc/{cp/constexpr.cc,cp/lex.cc,cp/Make-lang.in,c-family/c.opt,json.cc,json.h,tree.h}. Inspect GCC raw source on disk, treat it as read-only. Compiled baseline: build/gcc-gate/compiler-build/gcc/cc1plus. Probe logs under build/gcc-gate. + +## 5. Write ownership and coordination +Write scope: compiler-patches/gcc-16.2.0/0001-evaluator-events.patch; tests/corpus/frontend/verify-gcc-events.py +Generate/update the unified patch using private scratch build/gcc-gate/patch-author/ copies of only touched source files; no writes to official extract, compiler-build, installed gcc, shared VBS/CMake trees or sibling repositories. Root alone applies the patch to the owned release tree and rebuilds cc1plus. No branches, staging, commits, external messages or children. + +## 6. Implementation or investigation approach +In cp/constexpr.cc cxx_eval_call_expression admit direct FUNCTION_DECL with relevant real source after bound args (~4279). Open scoped attempt before lazy instantiate_decl 4291, actual body at 4531, capture ordinary scalar real get_value(res) at 4552 before destruction at 4576, post-clean-up outcome near 4653–4688. Distinguish real body/cache hit 4426, throw/jump_target/failure/overflow, void/constructors/unsupported; don't manufacture children for cached/folded results. For the actual returned INTEGER_CST, copy type precision, signedness and bits with correct truncation/negative handling. Never retain a GC pointer for serialization later. Disabled fast path cheap and bypasses formatting and I/O. Gate on private compiler option and validate private pipes. Locate cxx_init/cxx_finish in cp/lex.cc and registration/object list. Avoid interacting with ordinary output. Read-only planner identified exact source anchors and preflight approved this path. + +## 7. Interfaces and data contracts +NEW local compiler probe v1. Two fixed inherited pipes: fd 3 for control, fd 4 for event records. Opt-in private -fvls-observe, add -fvls-step for cooperative stops. VLS_GCC_NONCE is exactly 32 lower-case hex chars supplied by the trusted harness. Emit one bounded strict UTF-8 JSON object per LF line: {v:1,nonce,seq,kind,...}, contiguous seq from 0. hello first reports backend='gcc-16.2.0/vls-eval-1', supported kinds/capabilities. enter/body/value/cached/leave may carry integer frame and parent (null for root), name, source, line and byte column if established. value has an immutable value object {kind:'integer',precision,signed,bitsHex} with exact lower-case hex, or explicit unavailable; primitive widths 1..64. Treat body result as provisional until leave's outcome. stopped follows a supported value in stepping mode. Its seq is the stop generation. Accept only bounded control lines ' step|continue|cancel\n' for this stop. Wrong or missing controls cannot resume execution. frontendEnd indicates frontend finalization; wait status plus separate diagnostics determine final outcome. Helpers must escape or reject every invalid UTF8/control byte before formatting. Cap events (e.g. 4096), frame bytes 64KiB, control 4KiB, total trace (e.g. 1MiB), emit terminal truncation where possible; do not emit JSON as an unbounded printing side effect. + +## 8. Dependencies and integration +Root will syntax/build/test/apply patch to the verified source and relay compiler errors for you to fix in the patch. Source inputs for your harness are the existing gcc-live.cpp + controlled replacements in private temporary dirs. Test gcc disabled and enabled using the same source snapshot, no stdout ambiguity. Allow helper mapping in the test harness only for direct pipe setup. Root/other worker owns the separate bounded production-language C++ worker. + +## 9. Edge cases security and performance +Use narrow fixed-ASCII validated wire subset or strict writer for all text values; GCC json.cc emits invalid JSON for certain C0 strings. Detect partial writes/EINTR/errors, bound sizes before formatting. Nonce and stop generation prevent stale controls. Snapshot as provisional, only close success after cleanup; propagated jump_target takes precedence over normalized void. Capturing a tty/invalid fd must not stall ordinary compiler output. Explicit terminal reason/verified prefix on control loss. Backend never reaches out to a file or network for control. + +## 10. Acceptance criteria +Real runtime fixture: Ready=17/41 and identical >0 tests produce actual return pairs 17/34 and 41/82, extra bias=5 differentiates further. At held inner value prove same child PID is alive with no subsequent event until a matched step/resume, then observe outer return. Cancel another run at the same real stop; missing outer return and reaped process. Test backend/nonce/schema/sequence, parent/leave pairing, wrong control, EOF, scalar widths/negative or explicit unsupported, disabled parity/failed constraint. Ask root for patched binary when patch ready. + +## 11. Verification commands and evidence +Run codex-tasklint already done by root, git status --short --branch. Use patch --dry-run -p1 against clean GCC 16.2 source. Root runs dev cpp-gcc -c make -C build/gcc-gate/compiler-build/gcc -j2 cc1plus, supplies binary path. Run dev cpp-gcc -c python3 tests/corpus/frontend/verify-gcc-events.py --cc1plus /absolute/path/to/patched/cc1plus with bounded deadlines. Report each real result and unrun checks. + +## 12. Constraints and stop conditions +Stop for unresolved ambiguous value lifetime, need for project licensing decisions, changes outside assigned paths, or inability to prove live actual values. After two failed repair cycles provide root new hypothesis. No fabrication or progress claims before compiler-origin evidence. + +## 13. Authorization and decisions +User approved GPT-6.2 Astra at Max and local modified compiler prototype, licensing and distribution deferred. The fresh independent preflight's READY applies only to evaluator portion. Preserve other pending preflight gates. + +## 14. Return format +T-GCC-EVALUATOR-017 DONE/PARTIAL/BLOCKED, exact patch files/compiler members, private API, commands/exit/observed values/control, failure outcomes and integrations. diff --git a/docs/agent-workflow/tasks/T-GCC-IDE-008.md b/docs/agent-workflow/tasks/T-GCC-IDE-008.md new file mode 100644 index 0000000..54a5e97 --- /dev/null +++ b/docs/agent-workflow/tasks/T-GCC-IDE-008.md @@ -0,0 +1,48 @@ +# Observe resolved GCC source occurrences and witnessed definitions + +Task ID: T-GCC-IDE-008 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared VoidLanguageServer feat/implement-roadmap ca04975. Root has applied immutable first evaluator patch 4b4ff5b6 (build/gcc-gate/applied-0001.patch) on owned verified GCC 16.2.0 source in build/gcc-gate/gcc-16.2.0. T-PLAN-GCC-008 established real source anchors. Independent T-PREFLIGHT-GCC-008 approved this narrow slice subject to physical provenance, all-level tentative parsing, positive definition evidence and separate fixed IDE mode. Baseline eight tooling probes exercise actual compiler output. + +## 2. Objective and deliverables +Implement a second versioned unified patch and bounded real acceptance harness for narrow typed call/member occurrences and their observed source definition or declaration. Give root an apply-ready patch early. + +## 3. Scope and non-goals +Compiler-owned facts for direct parsed resolved ordinary calls and explicit fields in the fixed read-only GCC IDE experiment. No LSP methods, background build execution, inferred general reflection support, distribution or changes to launcher fixed evaluator flags. + +## 4. Files to inspect +Inspect patches/actual compiler members from T-GCC-EVALUATOR-017, tests/corpus/frontend/{gcc-queries.cpp,probe-gcc-tooling.py,verify-gcc-events.py}, actual gcc/cp/{parser.cc,decl.cc,lex.cc,vls-eval.{h,cc}}, c-family/c.opt, libcpp/directives.cc, gcc/diagnostics/sarif-sink.cc, linemap support and actual generated header flags in build/gcc-gate/compiler-build/gcc. + +## 5. Write ownership and coordination +Write scope: compiler-patches/gcc-16.2.0/0002-ide-occurrences.patch; tests/corpus/frontend/verify-gcc-ide.py +Author against private minimal member copies under build/gcc-gate/ide-author. Never write active GCC extract/build, 0001 or other owners' files. Root owns applying/rebuilding both. No staging, commits, branch changes, child agents, external sends. + +## 6. Implementation or investigation approach +Capture terminal unqualified-id token before opening paren in cp/parser.cc around 7150–64/8941, resolve after finish_call_expr 9129 using ordinary CALL_EXPR + cp_get_callee_fndecl_nofold and TREE_TYPE. Capture explicit p.x name at 9639, resolved COMPONENT_REF FIELD_DECL after final rejection check 9745–50. Suppress unresolved/tentative AST facts unless all enclosing levels committed (checking top alone wrong); use bounded deferred candidate buffer and all-level suppression or precise rollback. Witness actual definitions (e.g. real function body finalized cp/decl.cc ~20583), ordinary field origin via grokfield ~31583; synthesized/redeclared/implicit/macro/unknown cannot masquerade as a definition. No positive conclusions from matching spelling/lines alone. Verify stable physical token range for both use+target, primary fixed snapshot, no overlays beyond current invocation. Guard same-file #line/linemarker collisions using final seen_line_directive or genuine physical proof. Remember std headers may have numeric markers; be honest about degraded coverage. Collect compact owned metadata/indices with strict caps; never GC tree pointers after compiler hooks. + +## 7. Interfaces and data contracts +NEW private probe option -fvls-ide, distinguish hello capability and observed facts from evaluator-only mode, incompatible flag combos rejected or clear. Reuse v1 two-pipe strict writer/sequence/nonce/bounds in 0001 without changing existing evaluator behavior. Specify event names and fields, concrete byte ranges (one-based GCC raw bytes mapped to half-open span), invocation-local IDs, typed result and source authority, location-kind/explicit gaps, immutable snapshot identity supplied by harness. Emit IDE records only after confirming origin at finalization before frontendEnd. Narrow arbitrary operand within fixed query.cpp. Send root exact fixed mode requirements and wire early; separate owned IDE harness can use -fdiagnostics-format=sarif-stderr and -fvls-observe -fvls-ide. SARIF columns are display units; require byte/snapshot proof or mark diagnostic range unavailable. + +## 8. Dependencies and integration +Root is currently compiling 0001, will own incremental application to compiler-build. Observer 0001 owner may revise 0001. Coordinate with root before patches sharing writer/HELLO/lex/c.opt are re-based. Never run make in shared compiler-build. Use copied/narrow fsyntax-only checks while root builds. + +## 9. Edge cases security and performance +Bound all fields/events and candidate memory independent of translation-unit size; if obscured or incomplete, explicitly withhold affected facts. No arbitrary file reads from #line origin, no saved GC pointers, no unrestricted flags from projects. No exposed production compilers, no advertising unsupported IDE features. Test coordinates across tabs, combining and supplementary Unicode; conversion must detect ambiguity. + +## 10. Acceptance criteria +Real private compiler: saved point operand -> actually witnessed line 6 int, edit same call -> line 7 double, invalid edit -> genuine SARIF failure with no old overload, recovery -> line 6. Field use 6:46 -> actually witnessed field at 3:9. Add duplicate same-spelling occurrences with distinct physical use positions, forward-only declaration, same-file '#line 11' collisions, tentative or speculative/no admitted evidence, macro origin, tab/emoji differing display/byte/UTF16. Validate real hook output matches only observed identities; disabled evaluator baseline unchanged. + +## 11. Verification commands and evidence +git status --short --branch; patch --dry-run --fuzz=0 -p1 using private patch-0001 base; Python syntax checks with no checkout bytecode; root will run dev cpp-gcc -c make -C build/gcc-gate/compiler-build/gcc -j3 cc1plus. Run dev cpp-gcc -c python3 tests/corpus/frontend/verify-gcc-ide.py --cc1plus /absolute/path when root releases built binary, using temp private fixtures and timeouts. Give exact failing output/proof for skipped coverage. + +## 12. Constraints and stop conditions +Stop if unsupported physical coordinates or tentative behavior cannot be proven: report explicit withheld evidence, don't fabricate. Escalate if shared first patch API must be changed instead of additive second patch. On two failed repairs report new hypothesis. Limit private patch to approved GCC source version. + +## 13. Authorization and decisions +D-025 native primary, D-027/D-029 configured GPT-6.2 family Max, D-030 approved local patched compiler only. Review assignments stay GPT-6.2 Astra Max. Keep license and distribution deferred. This is the difficult direct IDE slice cleared under amended preflight. + +## 14. Return format +T-GCC-IDE-008 DONE/PARTIAL/BLOCKED with owned paths, exact baseline/patch digest, wire fields, commands and actual statuses, per-fixture positive and unavailable evidence, limitations and integration requirements. Return early patch-ready handoff and bounded real results. diff --git a/docs/agent-workflow/tasks/T-GCC-LEAF-009.md b/docs/agent-workflow/tasks/T-GCC-LEAF-009.md new file mode 100644 index 0000000..7c12c54 --- /dev/null +++ b/docs/agent-workflow/tasks/T-GCC-LEAF-009.md @@ -0,0 +1,48 @@ +# Launch the selected GCC frontend with isolated event and control pipes + +Task ID: T-GCC-LEAF-009 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer feat/implement-roadmap, baseline ca04975. User D-030 approved isolated GCC16 prototype and versioned hooks. T-PLAN-GCC-008 and T-PREFLIGHT-GCC-008 independently approved this launcher slice. Verified GCC 16.2 unmodified cc1plus at build/gcc-gate/unmodified/cc1plus; currently patched build under build/gcc-gate/compiler-build/gcc/. Root owns make and repository build files. + +## 2. Objective and deliverables +Implement the fixed-fixture private frontend leaf in C++ using VoidLibrary SHA/process-compatible FDs and OS limits. It must execute exactly the approved ELF bytes while providing distinct control, events and diagnostics streams. + +## 3. Scope and non-goals +Leaf process setup and dedicated test harness only. The supervisor launches its own trusted executable /proc/self/exe with a private --leaf mode and Void::Process. No production LSP hook, selecting tools from metadata, general-purpose flag forwarding, parent control/state machine or policy reconfiguration. + +## 4. Files to inspect +Read compiler-patches/gcc-16.2.0/0001-evaluator-events.patch, T-GCC-EVALUATOR-017 and T-PREFLIGHT-GCC-008 (wire), build/voidlibrary/current/include/Void/{System/{Types,Process},Crypto/Crypto}.hpp and generated src/System/Process.cpp; actual sibling source is read-only. See include/Void/LanguageServer/Support/RegularFile.hpp for Linux bounded regular capture. Source scratch receives the single reviewed fixture as input.cpp. + +## 5. Write ownership and coordination +Write scope: experiments/frontend/gcc-worker/Leaf.hpp; experiments/frontend/gcc-worker/Leaf.cpp; tests/native/GccLeaf.py +These three paths are exclusively yours. Use own ignored build/gcc-leaf-tests for isolated artifacts and witness program. Root owns normal executable main, architecture and build registration. No sibling or shared build-tree edits, staging/commits, further agents or user messages. + +## 6. Implementation or investigation approach +Implement vls::gcc::run_leaf(std::filesystem::path compiler, std::string_view expected_sha256, std::string_view nonce, bool stepping) returning 126 for setup failure, noreturn-by-exec on success; a diagnostic on stderr is bounded. Parent supplies cwd as private fixture directory. Consume stdin/control and stdout/events pipes from parent. dup to FD3 control, FD4 event before opening/moving checked compiler ELF to fd>=5, isolate compiler stdin/stdout on /dev/null, preserve stderr. Restrict raw FD and environment leakage. Validate pipes/nonce/SHA and regular binary. Bind digest to immutable bytes even if a developer recompiles in place (e.g. copy checked file into sealed memfd, verify SHA actual transferred bytes, set write/grow/shrink/seal and execveat AT_EMPTY_PATH). Report unsupported kernels/permissions explicitly. Preserve ELF loader semantics. On Linux, impose real RLIMIT_AS, RLIMIT_CPU, RLIMIT_CORE, bounded output/descriptor setup; avoid applying a file-size limit before copying the compiler. Spawn no shell/wrapper. FD and signal lifetime must be verifiable; failure never invokes a different binary. + +## 7. Interfaces and data contracts +Fixed compiler args: -quiet -std=c++26 -freflection -fsyntax-only -nostdinc -o /dev/null -fvls-observe, optionally -fvls-step, then input.cpp. C locale, empty PATH, VLS_GCC_NONCE exactly 32 lower-case hexadecimal, own explicit env only. No compiler flags, paths or shell spelling from project settings. Compiler protocol uses fd3/4. The SHA-256 (64 lower-case hex) is selected explicitly by trusted prototype parent; no implicit path-based trust. Keep worker and VLS project license deferred as authorized. + +## 8. Dependencies and integration +Root supplies main's --leaf mode + parent under disjoint paths. A direct private harness main in your ignored build can call run_leaf (report how). Root will integrate source and real cc1plus. Coordinate expected exit statuses for setup errors, wait/cancel and limits. Dedicated debugger worker is opt-in standalone, never advertise operations to LSP during this slice. + +## 9. Edge cases security and performance +Address fd3/4 collisions, CLOEXEC, files replaced while being read, non-ELF/script/nonregular input, inherited environment, empty/damaged digest, oversize compiler, symlinks and kernel refusing executable memfd. Use measured hard bounds allowing ~100MB test compiler. Avoid reading source bytes or home data in launcher. Parent owns subreaper/group cleanup; process-local error unwinding should release temporary descriptors. Bounded diagnostic text. + +## 10. Acceptance criteria +Run a real harmless compiled witness that verifies child FD3/control and FD4/event, raw stdout isolated and separate stderr. Verify exact args/nonce and parent env exclusion. Wrong SHA, nonregular/script, corrupted/truncated candidate, invalid nonce and FD setup must exit before execution. Test binary identity if named path replaced, verify AS/CPU/CORE limits. With private real cc1plus if ready, execute a hello and known fixture controls. Never use a mock to claim the real frontend ran. + +## 11. Verification commands and evidence +Use git status --short --branch, dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only experiments/frontend/gcc-worker/Leaf.cpp. Build standalone harness under build/gcc-leaf-tests and run python3 tests/native/GccLeaf.py using that harness. Run clang-format --dry-run --Werror (dev cpp) on your C++ files. Report actual results and returned signals/status. + +## 12. Constraints and stop conditions +After two unsuccessful attempts with the same diagnosis return exact errors and a changed hypothesis to root. Stop for need to change subprocess authority, prototype license or global machine limits. Do not make an unverified fallback to pathname exec. + +## 13. Authorization and decisions +User D-030 authorizes this local leaf and prototype. GPT-6.2 Astra Max. Independent reviewer approved launcher with explicit immutable execution and fd-before-open amendments. + +## 14. Return format +T-GCC-LEAF-009 DONE/PARTIAL/BLOCKED, paths, API/witnesses, exact limits, commands and results, real-vs-harness evidence and root wiring. diff --git a/docs/agent-workflow/tasks/T-GCC-PREP-008.md b/docs/agent-workflow/tasks/T-GCC-PREP-008.md new file mode 100644 index 0000000..2feef15 --- /dev/null +++ b/docs/agent-workflow/tasks/T-GCC-PREP-008.md @@ -0,0 +1,49 @@ +# Make the private GCC 16.2 prototype reproducible from its release archive + +Task ID: T-GCC-PREP-008 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Shared worktree feat/implement-roadmap ca04975. This is an implementation of the approved private GCC/D-030 feasibility prototype and reproducibility requirement. Official local release build/gcc-gate/gcc-16.2.0.tar.xz passed SHA512 c51c30ca7422d0cbecf504b2e0f33c3aca31e0f90a76b65217f465163fa6fa17b3f5de39e145c47e5bab90ac0ce7fff3b03c8d553ae36e01faaea5a50f8648d1. Two checked-in patches (0001 evaluator and 0002 IDE) have been applied to GCC with zero fuzz and compiled. Compiler prototype leaf and IDE/evaluator harnesses now work. Existing build has unreproducible absolute scratch driver and hand-configured paths. Root owns it; work only in new paths. + +## 2. Objective and deliverables +The earlier assignment returned HTTP 429 before writing the helper or instructions. The stock GCC/GDB experiment remains independent. Keep this opt-in reproducer confined to its two owned paths. +Provide a user-runnable, opt-in local preparation/build helper and short dedicated build/verification instructions for the two private compiler patches and reference header parity. It must reproduce cc1plus on this Nix host without editing installed toolchain or requiring /usr/include. Reuse checked source if available with verification; no binary distribution. + +## 3. Scope and non-goals +Only the local tool preparation and experimental README. Do not integrate an installed compiler into default VLS or choose a product license. Do not change existing active compiler build, baseline or GCC patches, user shell or external repo. No new package manager configuration. + +## 4. Files to inspect +Read build/gcc-gate/{release.sha512,configure.log,build.log,build-sysheaders.log,reference-cxx,reference-includes.json,macro-differences.json}, compiler-build/config.log actual invocations, GCC generated Makefile configure-* targets and gcc/Makefile stmp-fixinc. Read current repo compiler-patches and tests/corpus/frontend/{verify-gcc,verify-gcc-events,verify-gcc-ide}.py, tests/corpus/modules/verify.py, tools/prepare-voidlibrary. Existing dev cpp-gcc shell GCC wrapper includes headers reference must match. Avoid reading or logging private Nix/runtime config. + +## 5. Write ownership and coordination +Write scope: tools/prepare-gcc-prototype; experiments/frontend/README.md +Private build/gcc-reproduction allowed. Root owns other sources/docs and all shared build directories and source extracts. Never append to active build/gcc-gate files or touch siblings. No branch/commit/network publication/child agents or user sends. Download of official GCC public RELEASE into own ignored directory only if explicitly requested by tool flag; local archive already available for verification. + +## 6. Implementation or investigation approach +Use actual public release URL and pinned SHA512 checked before extraction, only owned generation output, guard against shared wrong dir/tar traversal, command nonzero/abort and partial build retry safely. Pin versions via release+patch contents and build config; avoid rewriting a previous known-good generation. Use own GCC source/build, patch --fuzz=0 in order, explicit absolute paths, build cc1plus directly via actual prerequisite targets or a legitimately fixed top-level build. Derive GMP/MPFR/MPC include/lib via explicit options or authoritative toolchain discovery (Nix split outputs, pkg-config may lack files); avoid host-specific hardcoded /nix/store paths in checked-in sources. Provide targeted flags/options for prerequisite discovery and verify your actual chosen command. Keep complete command arguments in local output state with no ambient environment dumps. + +## 7. Interfaces and data contracts +NEW standalone command tools/prepare-gcc-prototype: document actual options --archive FILE, --build-dir DIRECTORY or equivalent, -j/--jobs, optional environment Nix prerequisites. Must write machine-readable provenance and helper to use private cc1plus via the matching reference g++ wrapper for language corpus. Capture real reference include search output, PIE/default preinclude/predefines; check macro differences not guessed Nix paths. Use only trusted user-selected reference compiler, safe subprocess argument lists; avoid shell injection in generated wrappers for paths with spaces. Fixed leaf/direct IDE `-nostdinc` is separate from actual full standard lib editor-context gate. + +## 8. Dependencies and integration +Independent package under D-030 (local only). Root owns CPP run supervisor and both default builds; your helper can use all existing tests without altering them. Early final command-line recipe handoff helps root doc links. Verify genuine independent GCC build in your OWN output if feasible, run jobs<=4 while integrated builds active; ample disk but report any external prerequisite. Exact GCC 16.2 release archive available locally; gate all mutations on verified owned output. + +## 9. Edge cases security and performance +Concurrent runs for a destination must not corrupt it. Reject unverified archive, existing nonowned directory contents and symlink source/build retarget; standard archive tarfile data filter or properly checked extraction. Avoid source-directory mtime/patch state causing silent wrong binary reuse after patch changes; digest provenance. Make errors leave previous usable image; no automatic install, uploads or network fallback on failure. + +## 10. Acceptance criteria +Demonstrate --help, refusal of corrupt archive/occupied output, real clean/configure/targeted compile in isolated dir, exact two patch digest/ELF hash, cold/warm repeated invocation, actual private language19, evaluator and IDE harness checks (expected deliberate errors) + native module probes. If a long build starts, provide root exact PID/session and partial result; root can take over recorded handle. No substitute of stock cc1plus on verification. + +## 11. Verification commands and evidence +Use dev cpp-gcc -c tools/prepare-gcc-prototype with absolute verified archive and reserved build/gcc-reproduction (or unique child); print exact options used. Python syntax with ast.parse; lint new script via normal shell/check only. Record actual sha512sum outputs and source-target exit statuses, not just paths. Root builds regular VLS separately. + +## 12. Constraints and stop conditions +Stop for irreversible actions outside owned ignored folder, unexpected downloaded dependencies, changed/rebased GCC patches mid-build or inability to find building prerequisites. If host toolchain discovery fails, return actual error/hypothesis and continue independent documentation/testing. No replacing or distribution of proprietary binaries. + +## 13. Authorization and decisions +Approved local private versioned compiler prototype under D-030, native VBS remains main server build and VoidLibrary tracks main. GPT-6.2 Sol at Max for this general reproducibility package. Product compiler license distribution deferred. + +## 14. Return format +T-GCC-PREP-008 DONE/PARTIAL/BLOCKED, exact helper/docs, command lines, compiler/patch/source identities, proof of distinct private build, cold/warm & failure cases, residual host/tool prerequisites and live handle if applicable. diff --git a/docs/agent-workflow/tasks/T-GCC-SUPERVISOR-018.md b/docs/agent-workflow/tasks/T-GCC-SUPERVISOR-018.md new file mode 100644 index 0000000..2cafe95 --- /dev/null +++ b/docs/agent-workflow/tasks/T-GCC-SUPERVISOR-018.md @@ -0,0 +1,48 @@ +# Control and replay the isolated GCC evaluator in C++ + +Task ID: T-GCC-SUPERVISOR-018 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared repo feat/implement-roadmap at ca04975, existing implementation authorized. Exact GCC patch 0001 builds and real verify-gcc-events.py exits 0: 17/34 on old snapshot, 41/82 on edit, cancel 125, control failure 126. The patched cc1plus is 135307304 bytes (build/gcc-gate/compiler-build/gcc/cc1plus). Planner T-PLAN-GCC-008 and fresh reviewer T-PREFLIGHT-GCC-008 cleared the bounded control/replay design. Another worker owns Leaf.cpp/.hpp; root owns shared builds and LSP. + +## 2. Objective and deliverables +Implement the standalone local C++ prototype parent and replay entry point using Void::Process, VoidLibrary StrictJson facade and copied compiler records. Demonstrate live step, cancel and replay from the same recorded stop on the private compiler. + +## 3. Scope and non-goals +One active frontend per local prototype process, fixed leaf/input and integral evaluator only. No general compiler flags, editor integration, DAP, filesystem workspace discovery, public installation/distribution or production feature advertisement. + +## 4. Files to inspect +Inspect T-GCC-LEAF-009, T-GCC-EVALUATOR-017, compiler-patches/gcc-16.2.0/0001-evaluator-events.patch (source of truth), tests/corpus/frontend/verify-gcc-events.py, tests/corpus/frontend/gcc-live.cpp, docs/roadmap/{18-live-debugging,19-trace-replay}.md, include/Void/LanguageServer/Protocol/Json.hpp, Void::Process header/implementation in build/voidlibrary/current, System/TempDir, Crypto/Sha256 or actual Crypto.hpp APIs. Confirm actual FD/try_wait/terminate shape before implementation. + +## 5. Write ownership and coordination +Write scope: experiments/frontend/gcc-worker/Main.cpp; experiments/frontend/gcc-worker/Supervisor.cpp; experiments/frontend/gcc-worker/Supervisor.hpp; experiments/frontend/gcc-worker/Trace.cpp; experiments/frontend/gcc-worker/Trace.hpp; tests/native/GccSupervisor.py +Private build/gcc-supervisor-tests only for checks/harness. Leaf.hpp/cpp, GCC patches, both shared builds, server and docs owned by others. No Git/branch changes, public sends or children. + +## 6. Implementation or investigation approach +Implement private executable: --leaf validates argument form and dispatches vls::gcc::run_leaf(absolute selected compiler,sha256,nonce,stepping). Parent uses /proc/self/exe + Void::Process::spawn, search_path=false, explicit minimal env, new process group, PR_SET_CHILD_SUBREAPER before spawn. Copy explicitly chosen bounded fixture bytes into private TempDir/input.cpp, bind hash/compiler digest and fresh OS-random nonce. Run fixed leaf protocol with poll-driven bounded full-duplex I/O, separate events/stdout, controls/stdin and stderr. Maintain strict concrete state for observed hello/enter/body/value/cached/leave/stopped/resumed/terminal/frontendEnd, partial lines, running/stopped time, quota and PID. Treat copied value as provisional until leave, do not infer frames for cache. Persist captured source, immutable identity, terminal state and verified records to an explicitly named exclusive/new trace or owned directory. Provide offline replay at chosen event/stop/sequence, report matching frame/value stack from validated prefix with integrity checks. Input cutoff/cancel/truncation retains only verified prefix. + +## 7. Interfaces and data contracts +NEW standalone local prototype (root can register as vls_gcc_probe). Provide explicit self-describing CLI for run, step, cancel and offline replay, document actual spelling early. Live control messages from parent caller bind current nonce+stop and one use. Accept exactly one action from current stopped state; no queued preauthorization/predicted ordinal. In interactive mode consume + serialize commands, require actual resumed echo before post-stop movement; running cancel terminates group. Trace frames version 1, nonce, contiguous seq from 0; pin expected ELF identity, GCC handshake backend and PID, declared kinds, required frame+parent stack, value bit widths/format and null metadata. frontendEnd only indicates frontend finish; conclude success after balanced frames, EOFs, valid child wait + diagnostics. Replay must work with compiler absent; distinguish conclusive success, failed, partial, cancelled, terminal or quota, do not promote truncated open frames. Wire optional value projection JSON/stdout of prototype can be used by bounded integration test. Coordinate interfaces early. + +## 8. Dependencies and integration +Leaf owner separately implements and verifies prototype leaf, stable C++ signature in T-GCC-LEAF-009. Root may integrate your files as soon as present and will relay build errors. Use a temporary leaf-only testing source in your own ignored directory only for targeted failure-process fixtures; real compiler session/replay required once the leaf is ready. Keep supervisor/replay APIs usable by future authorized debugger work. + +## 9. Edge cases security and performance +Bound input before reading, messages/partial LF, bytes, trace entries, source, stderr, live wall and paused idle separately. Preserve compile return status and bounded stderr. Suppress SIGPIPE safely on closed controls. Block user speculative/duplicate/stale control; continued visits and handle generations must be explicit. Cancel/timeout handles stopped, running, leader-first and backpressured descendants; always drain both streams then terminate/reap group and adopted processes on deadlines. No leakage across process groups, no external sends or folder reads from manifest locators. Fail closed on malformed manifests, open evidence incomplete or wrong backend. No implicit overwrite of traces. + +## 10. Acceptance criteria +Exercise real fixed fixture original, edited, true pause+step then continue, cancel at inner with no outer, stale/double/resume-ack check, terminal on invalid/dead child, actual bounded stderr flood/partial frame and leader-first exit through private benign witness. Replay original 17/34 after source mutation to 41/82 and without usable compiler; cancelled prefix reconstructs copied provisional inner result (no invented successful return). Validate sections/corruption/truncation, source identity, nonce/seq, max limits, CPU/wall vs paused, deadline and absence of live descendants. Catch implementation defects; no fake compiler evidence. + +## 11. Verification commands and evidence +Use dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include and focused links to actual vls_protocol, Void_System/Crypto and pthread plus Leaf.cpp, or root built vls_gcc_probe. Run dev cpp-gcc -c python3 tests/native/GccSupervisor.py --help followed by documented real command with the absolute probe/compiler. Use dir build/gcc-supervisor-tests; root owns build/bootstrap and native build. Record real exit, ports use local pipes only, frame values and work not run. + +## 12. Constraints and stop conditions +Stop for changes outside the assigned prototype or a required change to the shared leaf API. Two failed repair attempts require changed hypothesis. On 429 or blocked leaf, deliver validated independent parser/replay, private controlled process tests and exact integration requirements. Never claim complete full roadmap18/19/20. + +## 13. Authorization and decisions +User D-030 approved local GCC instrumentation/worker prototype, D-025 primary VBS, D-027/029 GPT-6.2 family Max. This is the accepted prototype slice. Subsequent adopted frontend/IDE and DAP capability remain separate gates. + +## 14. Return format +T-GCC-SUPERVISOR-018 DONE/PARTIAL/BLOCKED, precise paths/CLI/API, real cc1plus launch and control, saved/replayed values, bounds/cleanup, validation commands and residual integration risk. Return early CLI and source readiness then final evidence. diff --git a/docs/agent-workflow/tasks/T-GCC-TRACE-019.md b/docs/agent-workflow/tasks/T-GCC-TRACE-019.md new file mode 100644 index 0000000..3636948 --- /dev/null +++ b/docs/agent-workflow/tasks/T-GCC-TRACE-019.md @@ -0,0 +1,48 @@ +# Validate evaluator event-time state and implement durable trace replay + +Task ID: T-GCC-TRACE-019 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Shared root feat/implement-roadmap ca04975. User D-030 approved private GCC hooks and worker. Real evaluator and sealed Linux leaf capture 17/34 after a pause/step, 41/82 on edited input, and cancelled 125/failed 126. T-PLAN-GCC-008 and T-PREFLIGHT-GCC-008 cleared bounded control/replay. Two prior supervisor assignments returned HTTP 429 before writing files. Root implements Main.cpp, Supervisor.hpp/.cpp and owns frozen Trace.hpp. This package is the independent trace/replay portion only. + +## 2. Objective and deliverables +Implement a bounded event validator, one-use stop control, private append-only journal and offline historical reconstruction behind the actual new Trace.hpp. Provide direct focused tests, then real integration through the actual supervisor operated by root. + +## 3. Scope and non-goals +Pure copied event/source state plus local persistence, no process launch, stdout protocol or CLI, server, DAP or shared build config. This task implements the integral-return prototype and its recovery behavior. + +## 4. Files to inspect +Read experiments/frontend/gcc-worker/Trace.hpp, compiler-patches/gcc-16.2.0/0001-evaluator-events.patch (actual serialization), T-GCC-SUPERVISOR-018, tests/corpus/frontend/verify-gcc-events.py, Protocol/Json.hpp implementation in src/Protocol, build/voidlibrary/current/include/Void/Crypto/Crypto.hpp, docs/roadmap/19-trace-replay.md. Source files under current worktree are authoritative. + +## 5. Write ownership and coordination +Write scope: experiments/frontend/gcc-worker/Trace.cpp; tests/debug/TraceTests.cpp +Use only those two tracked paths; root owns Trace.hpp, standalone main/supervisor, CLI and builds. For artifacts use your own ignored build/gcc-trace-tests. No Git ops, remote sends, sibling edits, child agents or shared package changes. + +## 6. Implementation or investigation approach +Validate bounded strict JSON v1 envelope, exact nonce and monotone integer seq. HELLO first expected version/backend/PID/capabilities: actual patch sends hello with 10 supported kinds. Require frame and parent on frame events, parent/top discipline, entered body then value (or cached); acknowledge actual matched control action for the correct stop before movement. Retain immutable copied integer precision, signed and lowercase bitsHex, distinguish unavailable and failing later cleanup. Track current active frames, provisional value, explicit partial and terminal reasons; don't infer values from names/sources. Preserve frame IDs even if nested calls or unexpected compiler ordering; check real event corpus (see witness test) before overconstraining. Read all docs for stdin control shape. A corrupt event must not advance state or poison last verified prefix. + +## 7. Interfaces and data contracts +Frozen API is Trace.hpp. create(output,source,compiler_sha,nonce,pid) exclusively creates a private journal (0600), hashes source, binds it+compiler identity to manifest, no overwrite. event(line without LF) validates and durably appends a complete record before publishing it to callers. authorize(stop,'step'|'continue'|'cancel') matches current unconsumed stop once, journals local command before return; stopped() then excludes consumed action while resumed remains required. ended() is true only after balanced frontendEnd. terminal() gives compiler terminal reason if any. inspection() returns owned JSON {nonce,sequence,stop,frames:[{frame,parent,name,value?,outcome?}],...}, inner frame last, sequence nullable before first event; integer value shape same as compiler. finish(outcome,exit_code,diagnostics) records verified process outcome separately; supported strings completed,failed,cancelled,truncated,expired. Completed requires genuine successful closed frontend, exit0. replay(journal,optional seq) returns same snapshot inspection including captured source, compilerSha256, sourceSha256, outcome and partial/corrupt status. seek returns state immediately after selected compiler event and before subsequent commands. Preserve read-only output with valid prefix on interruption. No arbitrary opens dictated by data in the file. + +## 8. Dependencies and integration +Implement the already-reviewed control/replay portion; no dependence on unfinished C++ supervisor for unit tests. Direct compile and test with C++26, small harness fixtures from captured real GCC event shapes. Notify root early if an actual wire mismatch affects integration. Root links implementations and performs real record/edit/replay after your handoff. + +## 9. Edge cases security and performance +Bound trace to actual 4096 events, ~1MiB payload, 4096 bytes per compiler frame, bounded source/diagnostic/metadata and command count. Use bounded file IO before allocation; corruption or truncation must not promote later records. Provide bounded record integrity, e.g. SHA-256 hash chained over length/previous record and exact bytes. Read only regular file; replay never executes commands or follows manifest paths. Handle short write, EINTR, concurrent or unsuccessful recording, partial tail and no in-place overwrite. Cap indexing and reconstruction memory; avoid copying all historical stacks per event. + +## 10. Acceptance criteria +Tests distinguish hello mismatch, bad ordinal/parent/frame, wrong integer bit length, stale/double control, resumed without command, cancellation prefix with open provisional frame, legitimate failed leave after provisional value, completion requires genuine wait outcome. Verify cursor snapshots and identical old source after disk edit/removal, truncation/tampering/replay-only without compiler, bounded corrupt line, exclusive create and no unintended artifacts. Root will exercise actual captured compiler stream+interactive supervisor separately. + +## 11. Verification commands and evidence +Use dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only experiments/frontend/gcc-worker/Trace.cpp tests/debug/TraceTests.cpp; link dedicated runner with build/bootstrap/libvls_protocol.a and Void_Testing,Void_Crypto,Void_System,Void_LogState,pthread. Run --list --no-color then --no-color. Formatter dev cpp -c clang-format --dry-run --Werror on your two files. Keep any fixtures private. + +## 12. Constraints and stop conditions +Stop for incompatible schema/API or new security authority; notify parent before changing public path/field. Two unsuccessful repair attempts require changed hypothesis. If dependency data does not support claimed completed trace report the gap explicitly. Never perform user-facing release/IPC work under this assignment. + +## 13. Authorization and decisions +D-027 Max explicit gpt-6.2-sol for general implementation, D-029 reviewer remains Astra Max; D-030 approved local GCC experiment and deferred distribution. Root owns process integration and launch trust. + +## 14. Return format +T-GCC-TRACE-019 DONE/PARTIAL/BLOCKED, exact files/CLI independent API, journal format/limits, evidence commands, actual assertions and residual integration. Return early parser ready status when root can link. diff --git a/docs/agent-workflow/tasks/T-MODEL-005.md b/docs/agent-workflow/tasks/T-MODEL-005.md new file mode 100644 index 0000000..41b328d --- /dev/null +++ b/docs/agent-workflow/tasks/T-MODEL-005.md @@ -0,0 +1,51 @@ +# Represent build contexts and publish results against their exact inputs + +Task ID: T-MODEL-005 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Work in /home/faumaray/Projects/VoidLanguageServer on feat/implement-roadmap (ca04975 with authorized foundation changes). T-PLAN-002 established the model order. T-PREFLIGHT-004 requires stable disk identity, owning translation units, ordered lookup evidence and readiness per operation. There is no existing build-model implementation. Read current files before writing. + +## 2. Objective and deliverables +Implement the provider-neutral value model, selection and revision/publication boundary for roadmap 05. Supply native Void::Testing tests and the interfaces providers 06/07 should consume. Return a brief interface outline early so root can prepare provider contracts. + +## 3. Scope and non-goals +Own only the new shared C++ build model and its focused tests. The root owns both build systems, session, provider adapters and cross-component wiring. Exclude processes, schema fabrication, compiler objects, database persistence and filesystem scans. Providers supply validated records and immutable data or specific unknowns. + +## 4. Files to inspect +Inspect docs/roadmap/05-build-contexts.md, 06-native-vbs-tooling.md, 07-compilation-database.md, 09-semantic-workers.md, 16-navigation-rename.md and T-PREFLIGHT-004. Read include/Void/LanguageServer/Documents/{DocumentSnapshot,DocumentStore}.hpp and Workspace/{Trust,Configuration}.hpp. The document worker confirmed DocumentSnapshot::same_input_as(const DocumentSnapshot&) for overlay versus stable disk inputs. Verify the final signature before compiling integration. Read tests/FramingTests.cpp for native VOID_TEST style. + +## 5. Write ownership and coordination +Write scope: include/Void/LanguageServer/Build/Model.hpp; src/Build/Model.cpp; tests/build/ModelTests.cpp +Other workers share this checkout. Create these NEW paths only, with scratch outputs under a unique build/model-005 directory. Never change branch, generated project state, others' work, or shared build files. Root registers targets and tests. + +## 6. Implementation or investigation approach +Implement immutable generation records and deterministic selection among all candidates for a source/owning TU. Preserve provider/target/profile and host-description versus target roles. Prefer verified explicit per-file override, then editor selection, then a documented deterministic fallback; keep a missing explicit override visible with typed unresolved status. Preserve structured override values suitable for the configuration owner; avoid writes during a model lookup. Keep original argument tokens/command distinct from analyzed tokens, provenance, cwd, selected toolchain/stdlib/environment identity, source mappings, missing metadata, prerequisite and artifact lifetime. Distinguish known-empty from unknown facts. Keep selection identity monotonic for A→B→A. Check equality of full values or canonical identities with collision-safe comparison; never derive identity by joining unescaped argv strings. + +## 7. Interfaces and data contracts +NEW Build model (exact C++ naming is local discretion) represents a retained generation, context alternatives, workspace/session identity and selection revision. Inputs bind the actual owning TU, source language and source mapping even when the requested document is a header. AnalysisRevision captures the document and dependency origins/content, relevant overlay/lookup epoch, workspace/provider/generation, context/selection, configuration, trust and backend/protocol. Use retained DocumentSnapshot::same_input_as or an equivalently stable key. Disk rereads with identical path/content and overlay epoch are equal. A reopened overlay with the same text is different. Bind ordered include/import search misses or a conservative monotonic invalidation epoch covering changes to all lookup roots. Readiness is operation-specific. Diagnostic/status data may be degraded with evidence; authoritative rename needs proven provenance, editability and complete affected contexts. Define any required unknown input as explicit. Avoid pretending external trust or filesystem events are synchronized unless the caller has supplied the corresponding state transition. + +## 8. Dependencies and integration +Keep publication verification and installation in a single sequenced transition, with cancellation/issuance and request identity. Concurrent stale completions cannot replace a newer result or remain visible after invalidation. Deliver a small backend-neutral immutable publication/token boundary that preserves validated data without callbacks that can re-enter under locks. Explicitly document how the owner supplies current input/revocation transitions. No AST pointers or global process authority. The Documents worker owns the snapshot contract. The trust owner supplies an opaque monotonic authority generation. Root links sources in VBS and comparison CMake after handoff. Providers 06 and 07 start only after this shared API is frozen. + +## 9. Edge cases security and performance +Reject invalid or duplicate context keys, unrelated roots and missing input identities before authoritative use. Preserve unsorted/duplicate original command tokens as meaningful data. Bound publication bookkeeping to active requests or discard completed/cancelled work; avoid retaining every historical result unboundedly. Keep immutable generations alive while in use. Selection/configuration/trust generations cannot be reused on an ABA transition. Do not copy full source content just to compare inputs. + +## 10. Acceptance criteria +1. Select two targets/profiles with conflicting defines for one source/header and retain all alternatives. Test explicit, missing and cleared override, deterministic reorder, host context and owning-TU differences. +2. Show unchanged reread can complete, same-text reopen and negative lookup invalidation reject old results, import/mapping/env changes distinguish inputs, and retention keeps the original generation alive. +3. Test cancellation/revocation and A→B→A between issue and completion, reverse completion/overlapping requests, atomic invalidation of current results, and bounds or retirement of outstanding tickets. +4. Assert incomplete metadata permits only the represented diagnostic/status capabilities and denies authoritative rename. Return all original test names and independent actual results. + +## 11. Verification commands and evidence +Use git status --short --branch, read selected sources and check graph coverage where indexed. Run dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only src/Build/Model.cpp tests/build/ModelTests.cpp. For executing tests use the tested local native libraries under build/native-validation/profiles/debug or comparison build/bootstrap; inspect real paths/symbols before linking. Coordinate with root if the final Documents implementation is required for runtime tests. Report actual runner --list, case count/exit and exact link/run commands. Run dev cpp -c clang-format --dry-run --Werror on the three owned C++ files. + +## 12. Constraints and stop conditions +Stop and notify root for an incompatible Documents API, cross-owner writes, unresolvable historical input semantics, or two failed trials of the same repair. Preserve useful independent implementation and tests. Never silently reduce authoritative coverage or couple the model to a candidate compiler. + +## 13. Authorization and decisions +The user approved all plans on a separate branch and GPT-6.2 family at Max, including generic runtime for the stricter effort setting. This difficult shared correctness boundary is assigned to Astra. No staging, commits, remote writes or sibling changes. No children and no independent user messages. + +## 14. Return format +T-MODEL-005 DONE/PARTIAL/BLOCKED, exclusive paths changed, concise interfaces for providers, decisions about equality/readiness and caller obligations, executed commands, case names/counts/results, open integration prerequisites or defects. Root owns integration and independent review. diff --git a/docs/agent-workflow/tasks/T-MODULE-CORPUS-011.md b/docs/agent-workflow/tasks/T-MODULE-CORPUS-011.md new file mode 100644 index 0000000..f857405 --- /dev/null +++ b/docs/agent-workflow/tasks/T-MODULE-CORPUS-011.md @@ -0,0 +1,48 @@ +# Connect the real stock GCC module corpus to the C++ module planner + +Task ID: T-MODULE-CORPUS-011 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Shared branch feat/implement-roadmap, ca04975 plus working tree. Roadmap 11 and T-PREFLIGHT-MODULE-011 cleared a pure ModuleGraph API. Its owner now released the public header for consumers. The existing tests/corpus/modules/verify.py compiles three named module generations with stock GCC16.2, checks 33 real P1689 observations, header-unit CMI shadowing and a failed scan that still emitted a rule. Until this task it validates output in Python only. + +## 2. Objective and deliverables +Make an explicit opt-in bridge between the actual GCC scanner invocations and the exact same C++ planner used by the server. The Python reference should exercise the bridge in its existing isolated fixture sandboxes. Include distinct ready DAGs for unbiased/biased generations and a true failed scan with retained GCC output. + +## 3. Scope and non-goals +Test-only integration. These closed, deliberately authored fixture inputs can be attested by the harness. No compiler invocation in product, metadata provider changes, editing ModuleGraph, test framework generalization or shipping this test helper. + +## 4. Files to inspect +Read tests/corpus/modules/verify.py and its source fixtures, include/vls/modules/ModuleGraph.hpp, src/modules/ModuleGraph.cpp, include/Void/LanguageServer/Build/Model.hpp, src/Build/Model.cpp, tests/providers/ModelTests.cpp, docs/agent-workflow/tasks/T-MODULE-GRAPH-011.md. Check exact field types and public behavior. Do not read unlisted repository contents for corpus data. + +## 5. Write ownership and coordination +Write scope: tests/modules/GccScanFixture.cpp; tests/corpus/modules/verify.py +You alone own these two files. ModuleGraph.hpp/.cpp and ModuleGraphTests.cpp belong to the model implementer; manifests, other tests, docs, private reference-compiler paths and Git belong to the parent. Preserve existing tests/CLI and current tree. No nested agents or user communication. + +## 6. Implementation or investigation approach +Use a small purpose-specific C++ fixture that decodes bounded real raw P1689 with decode_scan and chooses a real BuildGeneration built from the admitted ContextKeys and compiler invocations; populate census, evidence and private destinations from the fixture's actual command/source + transitive inputs/lookup identities. Existing Python harness owns exact compiler path, prepared fixture tree, private cwd and validates depfiles. Pass checked lengths/data (JSON via stdin or a private file) to helper without extra shell steps. Hash actual fixture inputs, compiler identity and appropriate options for command/compatibility, keep compatible legal per-TU -D differences; capture exact scan exit/status/output/cwd. Capture only explicitly known inputs and distinguish CMI warming; no exposing general project discovery. Root will inspect and rerun the real compiler checks. + +## 7. Interfaces and data contracts +NEW optional --planner PATH on verify.py (existing --cxx and ordinary no-planner command unchanged); NEW fixture executable target vls_module_scan_fixture, single source tests/modules/GccScanFixture.cpp. Communicate argv early. Keep nonzero errors distinct from expected typed blockers. Ready DAG order includes importer last; inspect internal partition/unknown import-only kinds and topological reverse edges when possible. Accept context keys and original spellings, retain actual scan revision/census. Use fixture-specific physical claims only when supported by this run. If a header-stage provenance claim is missing, test an explicit pending outcome. + +## 8. Dependencies and integration +Frozen ModuleGraph header exists, ModuleGraph.cpp passed GCC16 syntax. Root owns CMake and VBS registration of the helper, can start building after your path exists. Independent unit tests cover deep/failure/CMI provenance combinations. This task adds the true cross-component scan witness. + +## 9. Edge cases security and performance +Limit test input and subprocess output, use 30s deadline like existing corpus, keep temporary cache isolated. Do not compile arbitrary rows/scan commands from a database. Compute expected outcomes from the fixture design independently of the produced graph order. Different private invocations can use the same label, values reflect only observed GCC 16.2. Avoid accepting missing stderr/rule as success. + +## 10. Acceptance criteria +Both stock --cxx runs with/without the bridge succeed. In the real biased context internal :detail precedes :api, primary, importer. In the unbiased context :detail is outside the importer closure. Source edit and legal reader -D variations retain correct domain-specific result. Positive rule on exit1 cannot authorize planning. Preserve all 33 scan checks, 17/41/48 outcomes and old generation 17 and header11/29. A malformed/wrong primary-output fixture fed to the real decoder returns nonready. Add an additional true header-CMI witness only when current captured provenance is provable. + +## 11. Verification commands and evidence +Initial dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only tests/modules/GccScanFixture.cpp. Use python3 -B tests/corpus/modules/verify.py --help and dev cpp-gcc -c python3 -B tests/corpus/modules/verify.py --cxx g++ --planner /absolute/helper after linking; root builds both systems and reruns. Use build/module-corpus-011 for isolated intermediate outputs only. + +## 12. Constraints and stop conditions +Return early ready-to-build source notice. Do not select production backend, change flags in the reference script except what is needed to capture evidence, or invent global project/source authority. If a missing library interface prevents integration, send a minimal counterexample to parent, continue independent real controls. + +## 13. Authorization and decisions +User authorized full roadmap in separate branch; D-025 native VBS, D-027 GPT-6.2 family Max. Regular stock GCC16 tests and the independent approved module planner contract are in scope. No staging/commit/push/shared-build mutations. + +## 14. Return format +T-MODULE-CORPUS-011 DONE/PARTIAL with syntax/link/test exits, real compiler identity, counts, fixture contract, exact planned order and failure witnesses, residual limitations. diff --git a/docs/agent-workflow/tasks/T-MODULE-GRAPH-011.md b/docs/agent-workflow/tasks/T-MODULE-GRAPH-011.md new file mode 100644 index 0000000..f87bd96 --- /dev/null +++ b/docs/agent-workflow/tasks/T-MODULE-GRAPH-011.md @@ -0,0 +1,51 @@ +# Plan C++ module builds from versioned compiler scan evidence + +Task ID: T-MODULE-GRAPH-011 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared feat/implement-roadmap ca04975. Actual GCC 16.2 corpus in tests/corpus/modules/verify.py reads P1689R5 v0/rev0 single rules, changes named partition requirements with macros and exposes a cold header-unit scan missing a later import. Warm validated builds obtain 17/41/48; old reader remains 17. T-PLAN-SEMANTICS-010 provided the module package. Existing BuildGeneration/ContextKey and immutable AnalysisInputs hold authority/input identity. Core graph currently absent. + +## 2. Objective and deliverables +Implement the compiler-independent module scan decoder and dependency planner used by the semantic worker. Expose deterministic prerequisite order for a requested owning TU, reverse consumers for invalidation, and structured blockers with truthful completeness. Supply focused C++ tests. Root integrates both build systems and runs the real GCC fixture through this new C++ path. + +## 3. Scope and non-goals +Graph construction and immutable evidence only inside VLS. No compiler/descriptor spawning, file reads through graph data, module file format assumptions, public LSP advertisement, frontend choice, shared build wiring, new source parser or edits outside ownership. + +## 4. Files to inspect +Read docs/roadmap/11-cpp-modules.md, tests/corpus/modules/verify.py and fixtures, build/gcc-gate/private-modules.log, include/Void/LanguageServer/Build/Model.hpp, include/Void/LanguageServer/Protocol/Json.hpp (bounded parser and type accessors), tests/providers/ModelTests.cpp for actual runner idiom. Consult P1689R5 directly (open-std.org/jtc1/sc22/wg21/docs/papers/2022/p1689r5.html); GCC output supplies fewer fields than the general format. + +## 5. Write ownership and coordination +Write scope: include/vls/modules/ModuleGraph.hpp; src/modules/ModuleGraph.cpp; tests/modules/ModuleGraphTests.cpp +Shared files marked above are yours only after root explicitly dispatches this task following preflight. Root owns real compiler harness, build manifests, docs and all integration. Use isolated build/module-graph-011 for temporary checks. No staging, commits, branch changes, other workers, or user communication. + +## 6. Implementation or investigation approach +Decode one expected primary output per compiler invocation with Protocol::parse_json and its helpers; validate types, GCC envelope and optional authority-bearing fields before producing owned data. Bind it externally to its real exit status, scan method/completeness, file/command/provider revision, immutable source and lookup inputs. Allow explicit authoritative header-unit identities, path/spelling ambiguity must degrade. Never infer unit semantics from filename. Missing source, failed pass even with viable-looking rule, cold incomplete header/macros, duplicate providers, missing provider, cycle, mismatched domain and oversize need typed outcomes. + +## 7. Interfaces and data contracts +Bind each consumed header-unit CMI to its immutable staged artifact generation and matched current header/transitive contents, compiler/domain and lookup identities; a successful warm scan with an old CMI misses a macro-conditioned import. A bare warm flag or a depfile containing just a CMI cannot provide completeness. A -MMD scan needs independent immutable system-include coverage; -MD textual dependencies or equivalent evidence cover relevant inputs. -M -MG can be used warm as well as cold, so the scan mode alone never upgrades completeness. GCC can emit identical import-only rules for a module implementation and an ordinary importer with identical expected output. Keep that unit kind unknown unless independently evidenced. +The input owner supplies a closed, revisioned census of eligible per-TU ContextKeys for the requested linked target/domain, or a compatible per-importer census when visibility differs. Explicit membership is distinct from ABI compatibility. Reject ambiguous/missing censuses and unknown claims from failed or omitted eligible scans before claiming ready. Cover membership/lookup changes and missing or duplicate claims in invalidation evidence so adding a previously unknown provider invalidates old observations. Prove unrelated complete cycles do not block a requested acyclic component. This decoder accepts the observed GCC 16.2 single-rule version 0 revision 0 variant of P1689R5; the published paper describes version 1 revision 0. Refuse unsupported versions with a typed result. Bind expected primary-output to the admitted invocation working directory and its exact expected spelling or a proven matching identity. +NEW API in namespace vls::modules, exposed through ModuleGraph.hpp. Provide read/decode_scan(p1689_bytes, expected_primary_output) -> expected and build_module_plan(graph inputs, requested TU/context) -> owned plan with order, reverse invalidation and typed blockers. Freeze exact names to root early. Scans carry Build::ContextKey or equivalent unambiguous owning TU/context identity, full generation scope, source/dependency observations and verified compatible module-domain identity. Distinguish TU command identities from module compatibility: legal per-TU -D or -o variations cannot prevent deliberately admitted compatible providers. ABI-affecting configuration and lookup scopes cannot mix on name. Preserve is-interface false, header lookup identity (where emitted), primary-output equality and source convergence. Epoch/current checks belong to revision owner. + +## 8. Dependencies and integration +T-PLAN-SEMANTICS-010 early plan accepted for preflight. This is the pure graph used by a future real worker/scheduler. Root verifies current stock GCC via full module corpus and an integration bridge consuming actual P1689 scan output; return interface early to allow this. No production backend selection required to model observations. + +## 9. Edge cases security and performance +Bound JSON bytes/depth and per-rule/collection/string/aggregate sizes before expensive work; cap graph nodes/edges/traversal. Avoid process-stack overflow on deep chains, arbitrary path normalization, global name-only matches, unsafe cross-context reuse, repeated O(N²) scans or exponential walking. For blockers outside a requested independent component distinguish global collection incompleteness from a proven conflict unrelated to that component. Definition of input coverage must account for unknown provider claims and duplicate records, including failed scans. + +## 10. Acceptance criteria +READY from the independent reviewer. Include a new file changing __has_include and attaching a new edge, and a renamed provider introducing a duplicate while the eligible membership stays fixed. Equal private output labels in distinct invocations are legal and differ from a writer collision of actual output identity. +Assert ordered transitive partition/primary/importer, implementation and internal partition, same-name compatible duplicates vs incompatible contexts, unprovided std/header, self+multi-node cycles, retained previous context after source edit, reverse invalidation, context switch, header shadowing and cold/warm conditional import. Document what cannot be inferred from GCC scan. Test malformed/unknown wire semantics, successful rule with failed compiler exit, deep/legal bounds, semantic distinction of absent vs malformed scanner evidence and explicit incompleteness. + +## 11. Verification commands and evidence +Use dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only src/modules/ModuleGraph.cpp tests/modules/ModuleGraphTests.cpp. Use Void::Testing runner and actual resulting nonzero registered suites via root build or temporary separate link with existing build/bootstrap artifacts. Do not configure shared build dirs. Root provides integrated target and binaries. Record exact observed results and distinguishing failure inputs. + +## 12. Constraints and stop conditions +Stop for data/authority the graph cannot establish, expose typed pending status, send root the exact missing evidence and complete independent cases. No guesses about real loaded imports, generated code, artifact compatibility or private fragment support. Do not choose backend/distribution or expand code ownership. + +## 13. Authorization and decisions +User authorized full implementation, separate branch, VBS primary, GPT-6.2 Max (D-022/025/027); local compiler experiments only D-030. Modules are first-class user requirement. No out-of-repo writes except owned temporary compiler outputs under this checkout. + +## 14. Return format +T-MODULE-GRAPH-011 DONE/PARTIAL with public API, invariants, touched files and exact commands/results; send root stable headers early, concrete limits/open obligations at handoff. diff --git a/docs/agent-workflow/tasks/T-NATIVE-001.md b/docs/agent-workflow/tasks/T-NATIVE-001.md new file mode 100644 index 0000000..3e14778 --- /dev/null +++ b/docs/agent-workflow/tasks/T-NATIVE-001.md @@ -0,0 +1,74 @@ +# Build, test and install the server with native VoidBuildSystem + +Task ID: T-NATIVE-001 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Baseline /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975. The working tree includes the root CLI repair and user-owned foundations authorized for continuation. D-021 follows VoidLibrary main, tested at 7d7d23e. D-025 makes VBS primary. Root built a working VBS 6c225c2 seed from committed sources under build/tools/vbs-6c225-bin. A native Void::Testing test passed with all five dependency modules and a rejecting cmake at the front of PATH. + +## 2. Objective and deliverables +Supply a usable, ordinary native VBS description for the server and its real tests. Provide an explicit dependency preparation/update path for upstream main and a separate local source override. Validate debug build/test and staged installation. Root will integrate the build of subsequent features. + +## 3. Scope and non-goals +Native declaration, dependency management, real test registration and resolution of the built vls executable. Preserve the existing CMake bootstrap as a comparison build. Root owns README, application code, native tooling consumption and sibling repositories. + +## 4. Files to inspect +Inspect CMakeLists.txt, cmake/VoidDependency.cmake, tests/CMakeLists.txt, tests/Registration.cmake and the five existing *Tests/Capabilities translation units. Inspect build/tools/vbs-6c225-src/{build.cpp,include/Void/Build.hpp,recipes/VoidLibrary/VoidLibraryRecipe.cpp}, build/bootstrap/_deps/voidlibrary-src/{cmake/VoidTesting.cmake,include/Void/Testing/Test.hpp}. T-PLAN-002 and the fresh preflight are binding. + +## 5. Write ownership and coordination +Write scope: build.cpp; build.profiles.cpp; tools/prepare-voidlibrary; tests/FramingTests.cpp; tests/JsonTests.cpp; tests/LifecycleTests.cpp; tests/JsonCapabilities.cpp; tests/ProcessTests.cpp; tests/TestExecutable.hpp; tests/NativeRegistration.cpp; tests/CMakeLists.txt; .gitignore +These are exclusive only until handoff. Existing dirty cmake/VoidDependency.cmake is outside your scope. Do not change branches or stage, commit or push. The VBS tool generates runtime .vbs and vbs.lock. Ignore only generated root state and respect existing files/links. Build and install exclusively under build/native-validation and build/native-install. Other agents share the checkout. Keep schema, docs and all other source files with their owners. + +## 6. Implementation or investigation approach +Use project.static_library/executable/test and the explicit C++26 and reflection settings. Link the actual Void modules through .native_builder on a path dependency. Use the built-in debug/release profiles if adequate. Populate a managed checkout of main by explicit preparation; select immutable revision for each build, retain real checkout provenance, fail clearly if missing. Never execute network/git inside build.cpp. Honor an explicit VLS_VOID_SOURCE_DIR development override. Distinguish source provenance for updates and overrides and prevent accidental modifications to arbitrary directories or the sibling checkout. Keep preparation short and use verified tools. Native VOID_TEST(suite,name) preserves existing names/assertions without a CMake scanner. Retain CMake test registration. Native subprocess tests must launch the sibling vls from the same output/profile. Add a native registration witness that checks the three inventories and executes the named body; never accept an empty suite. Use public native target edges and installation APIs. + +## 7. Interfaces and data contracts +Existing targets vls_protocol, vls, vls_unit_tests, vls_json_capabilities and vls_process_tests. New build.cpp exports void build(Void::Build::Project&). Use native runtime location of the test executable (Linux supported) if the CMake VLS_EXECUTABLE definition is absent. NEW tools/prepare-voidlibrary documents its own usage and leaves the managed source usable by ordinary VBS commands. Preserve every test's suite/name and assertion semantics. Future suites must be addable without hardcoded machine paths. + +## 8. Dependencies and integration +After preflight, you are sole owner of the native descriptor and changes to the five test declarations. Root will wait before wiring other components into build.cpp or adjusting test expectations. Existing bootstrap source linter/CTest and the VBS seed run in dev cpp-gcc. Tests added elsewhere by foundation tasks will be integrated by root. Return source paths and registration changes for the reviewer. + +## 9. Edge cases security and performance +Main updates must preserve existing managed checkout consistency if offline, interrupted or concurrent. Prefer atomic publication of a complete source tree or an equivalent documented failure-safe preparation. A user-supplied override is read-only. Never copy an arbitrary sibling working tree or untracked files. Reject invalid override paths or wrong sources. Do not execute target metadata or add a CMake executable action. Preserve user-owned compile_commands.json. Test artifacts, dependencies and installs belong under this project's ignored build tree. + +## 10. Acceptance criteria +1. Clean native run builds VLS dependency and test objects without invoking CMake or reusing CMake-built project libraries. +2. Actual native inventories contain at least the original 22+6+9 names without duplicates, and the named exact_frame_limits body executes. Preserve behavior for failed cases and empty inventories. +3. Native process tests launch this profile's actual vls. Help/version/stdio behave as before. Native install produces a working bin/vls. +4. Explicit local override and managed upstream-main paths are distinguishable. Existing CMake comparison remains green. Confirm which checks were observed and which root still needs to run. + +## 11. Verification commands and evidence +From repo root the proven seed is build/tools/vbs-6c225-bin/bin/vbs. Use dev cpp-gcc -c with the executable and `test --project . --build-dir --profile debug --jobs 4`. Use install --help to verify syntax and stage under build/native-install. For no-CMake proof put build/vbs-native-probe/trap at the front of PATH within dev cpp-gcc. Root demonstrated the same flags on two probes. List the resulting three test binaries with --list --no-color and run one with --filter '^FramingTests.exact_frame_limits$'. Compare original suite lists when present under build/bootstrap/tests. CMake comparison command: dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure after rebuilding. Format changed C++ files with dev cpp -c clang-format. + +## 12. Constraints and stop conditions +Stop on unowned edits, a required VBS/Library patch, a request for global installation or two failures of the same repair. Capture command, stderr and a distinguishing hypothesis. If isolation is unclear, ask root before modifying another path. No cleanup outside unique owned scratch. + +## 13. Authorization and decisions +D-021, D-022, D-024, D-025, D-026 and D-027. User authorized the full roadmap, branch, native builder and GPT-6.2 Sol with Max after escalation. Dispatch only after root supplies the preflight verdict. Interpret a passed subset accurately. + +## 14. Return format +Return T-NATIVE-001 DONE/PARTIAL/BLOCKED, files changed, usable commands, test IDs and counts, fetched/override revisions, observed exit statuses, artifact locations and remaining defects. No child agents or independent messages to the user. + +The resumed working tree now includes two additional root-owned ordinary tests +in tests/JsonCapabilities.cpp. Convert them along with the original declarations. +Current inventories are 22/8/9 (39 cases). T-REVIEW-003 found an upstream numeric +precision and range defect; preserve these failures and their exit status until +fixed. Native parity compares real case outcomes across both builds and requires +all original 37 to pass. Use `--list` to discover the exact working-tree baseline. + +T-PREFLIGHT-004 correction, accepted by root. VBS snapshots path dependencies +recursively and chooses a dependency's build.cpp over its native Void recipe. +Hand VBS an immutable, project-owned source generation prepared from allowlisted +tracked build inputs only. Apply this to both upstream main and explicit local +overrides. Include real tracked C++ headers and the compiled sources for the +module closure; retain the src/Core directory used for recipe detection. Reject +a new tracked root build.cpp pending review and exclude untracked files/links, +dotfiles and unrelated paths. Do not point .path() at an external working tree. +Keep selected path, revision and relevant dirty/content identity in provenance. +An explicit local override should capture tracked source edits coherently or +reject a changing input cleanly. Publication is atomic. A build keeps its +resolved immutable generation even when another preparation selects a new one. +Check with benign untracked canaries, a tracked descriptor fixture and a failed +refresh that leaves the prior generation usable. These checks use isolated +fixtures. Make the managed generation path discoverable for root's integration. diff --git a/docs/agent-workflow/tasks/T-NATIVE-PREP.md b/docs/agent-workflow/tasks/T-NATIVE-PREP.md new file mode 100644 index 0000000..9af72c3 --- /dev/null +++ b/docs/agent-workflow/tasks/T-NATIVE-PREP.md @@ -0,0 +1,51 @@ +# Prepare immutable VoidLibrary source generations for the native VBS recipe + +Task ID: T-NATIVE-PREP +Role: astra_implementer +Status: READY + +## 1. Context and baseline +/home/faumaray/Projects/VoidLanguageServer on feat/implement-roadmap at ca04975, shared checkout. T-NATIVE-001 Sol terminated on provider HTTP 429 before writing files. T-PLAN-002 is complete. T-PREFLIGHT-004 cleared the native build subject to restricting VBS path input to prepared tracked sources. Root now owns build.cpp and the test migration. This separate assignment owns only the more demanding dependency acquisition/publishing boundary. + +## 2. Objective and deliverables +Implement tools/prepare-voidlibrary to prepare VoidLibrary main or an explicitly selected local checkout as a coherent, immutable source generation. The normal VBS descriptor reads build/voidlibrary/current, a symlink to build/voidlibrary/sources/<64-lowercase-hex-digest>. Give root usable commands and verify source-only safety and update behavior. + +## 3. Scope and non-goals +Dependency preparation, provenance and its targeted integration checks. Root implements native compile/install/test targets. No changes to VBS/VoidLibrary source, checkout or configuration. Keep the implementation small, understandable and Linux-compatible. A short Python stdlib or shell utility is appropriate for explicit developer preparation. + +## 4. Files to inspect +Read docs/agent-workflow/tasks/T-NATIVE-001.md including T-PREFLIGHT-004 correction. Inspect build/tools/vbs-6c225-src/src/Package/Fetch.cpp:145, src/Provider/Provider.cpp:1046 and recipes/VoidLibrary/VoidLibraryRecipe.cpp. VBS recognizes a prepared VoidLibrary by include/Void and src/Core, and chooses a root build.cpp over the native recipe. Existing main 7d7d23e. No broad scans of live sibling or ignored state. + +## 5. Write ownership and coordination +Write scope: tools/prepare-voidlibrary; tests/native/Preparation.py +Your sole production-owned file is the preparation tool. Optional named test file covers meaningful update/race/provenance behavior. Ignore scratch under build/preparation-check. Root owns build.cpp, registry and all other files. No staging/commits/branch changes in this repo or any existing repo. No interaction with global configuration or project-side compdb. + +## 6. Implementation or investigation approach +Resolve official https://git.faumaray.com/Void/VoidLibrary.git main explicitly, never a committed SHA. Support VLS_VOID_SOURCE_DIR (or --source plus the same env) for local checkout. Use only allowlisted tracked C++ headers/source files needed by the native module closure. Cover current five modules, Crypto/Text for reviewed foundations and transitive modules in the recipe; keep src/Core present. Exclude untracked inputs, root build descriptors, hidden/secrets, unrelated paths, gitlinks and symlink escapes. Reject a tracked root build.cpp before invoking any dependency-provided behavior. Avoid invoking project filters/hooks/scripts or following malicious local-tracked source symlinks. Local tracked edits may be captured coherently or explicit instability refused. For clean primary source use immutable Git objects or equivalent. Stage only inside an owned temporary directory. Validate complete source, record revision/content identity and source path/kind in metadata, publish the full generation and then atomically switch current. A failed preparation leaves the previous source in place; duplicate/concurrent calls preserve complete generations. Do not delete old generations still in use. Diagnostic errors must avoid exposing arbitrary file contents. + +## 7. Interfaces and data contracts +Fixed interface between workers: native build.cpp canonicalizes build/voidlibrary/current and verifies its parent is the real build/voidlibrary/sources. Each generation includes include/Void/Data/StrictJson.hpp and src/Core/, excludes build.cpp. Sources directory name is content/provenance-addressed. Write one bounded UTF-8 metadata file at generation root named provenance.json with at least revision, source kind (main/local), source path for local, dirty flag and content identity. Communicate a concrete example and exact CLI. Keep preparation outside VBS; descriptor performs no Git/network operations. + +## 8. Dependencies and integration +Fresh reviewer accepted native target/install work when this guard is included. Root works on those targets concurrently. Local origin is a user-selected dev override, upstream main default always resolves the official remote. Tests under T-REVIEW-003 intentionally expose two separate JSON faults; no dependency parser/code edits. + +## 9. Edge cases security and performance +VBS recursively snapshots path deps. Never hand it the external live directory. Benign untracked canary and untracked descriptor must not appear in the published generation. A tracked descriptor must be rejected. Avoid plain recursive copy. Preserve old generation on interrupted/offline fetch, distinct local changes, and failed validation. Use a narrow trust boundary around the tool's own cache and path selection. Test fixtures must never write to existing checkout Git state or local secrets. + +## 10. Acceptance criteria +1. Real upstream main and explicit local preparation each yield an inspectable immutable source tree and SHA/dirty provenance. +2. CMake/VBS-ready source directories and needed modules are present. No extra descriptor/canary, no symlink excursion, no source mutation. +3. Repeated/failed/concurrent preparations preserve a previously captured generation and atomically publish a complete current target. +4. Report executable path and command so root can run native VLS build now. + +## 11. Verification commands and evidence +From repo root compare git ls-remote --exit-code https://git.faumaray.com/Void/VoidLibrary.git refs/heads/main, and git -C build/bootstrap/_deps/voidlibrary-src rev-parse HEAD. Root observed both 7d7d23e. Run the newly implemented CLI in its documented default and explicit override modes, and a focused fixture test isolated in /tmp or build/preparation-check. To avoid cross-worker races, alert root when build/voidlibrary/current is ready before toggling it; run adversarial fixture tests in a separate temporary repo view/store. Root runs integrated VBS and CMake tests. Do not pin or stage anything. + +## 12. Constraints and stop conditions +Stop before sibling changes, source installer execution or dropping required controls. If two repair cycles fail for the same check, return evidence for a revised hypothesis. No global changes or worker spawns. + +## 13. Authorization and decisions +D-021 and D-025 require unpinned main with native VBS. D-022/D-026 authorize this branch and full implementation. D-027 authorizes GPT-6.2 Astra at Max for difficult implementation, including this reviewed dependency handoff. This is a separate high-risk assignment split from the failed Sol task; root owns the remaining integration. + +## 14. Return format +Return T-NATIVE-PREP DONE/PARTIAL/BLOCKED, files, CLI/path interface, verified source generations, checks/exit codes, unrun checks and integration notes. Notify root as soon as the first valid generation is available. No independent user messages. diff --git a/docs/agent-workflow/tasks/T-PLAN-002.md b/docs/agent-workflow/tasks/T-PLAN-002.md new file mode 100644 index 0000000..d065056 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PLAN-002.md @@ -0,0 +1,149 @@ +# Plan foundation implementation against the resumed checkout +Task ID: T-PLAN-002 +Role: astra_planner +Status: READY +Dispatch: user approved the generic runtime role after escalation. Select gpt-6.2-astra at Max for the astra_planner assignment. + +## 1. Context and baseline +Cwd/repository /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at +ca04975d545efd4a891ee90edf22f130069bd191. User now requests implementation of all27 +roadmap parts, preserving gates and acceptance, and explicitly requires Max effort. +The named roles are fixed at XHigh. The user approved an explicit Max override +on the generic runtime and then selected the 6.2 family for all assignments. +Existing uncommitted foundation code is available: user confirmed no active writer. +Root has preserved its16-file baseline in build/goal-baseline-20261127. +Root additionally repaired src/main.cpp bare '--' handling and updated workflow docs. +VoidLibrary main tested at7d7d23ec0a6a55d4b30921432fa215b29a29e59b; fetched build now +passes all4 CTest entries (22 unit+6 JSON+9 subprocess bodies plus registration). + +## 2. Objective and deliverables +Return a dependency/invariant map and exact implementation wave for native VBS +primary build support (01/26), then03/04/05 with protocol consolidation and real LSP +document synchronization. User D-025 explicitly makes VBS primary now. Preserve the full +27-part objective. Distinguish immediate executable work from later frontend/VBS/ +debugger gates. Provide proposed interfaces, disjoint ownership, concrete acceptance +tests, migration order and unresolved consequential decisions for fresh preflight. +Do not approve your own plan or claim this report is implementation. + +## 3. Scope and non-goals +Assess the existing uncommitted Protocol/Documents/Workspace implementation and +how to integrate it, rather than replacing it wholesale or inventing a new namespace. +Plan BuildContext/AnalysisRevision contracts before provider tasks06/07. +Do not implement application code, compiler semantics, a competing JSON parser, +sibling producer changes, new tool installations, license selection or releases. + +## 4. Files to inspect +AGENTS.md; docs/agent-workflow/STATE.md,TASKS.md,DECISIONS.md, +RESUMPTION-2026-11-27.md and VERIFICATION.md; docs/roadmap/README.md,REQUIREMENTS.md, +ARCHITECTURE.md and03-documents-positions.md,04-workspace-configuration-trust.md, +05-build-contexts.md,06-native-vbs-tooling.md,07-compilation-database.md, +09-semantic-workers.md,10-scheduling-resources.md,16-navigation-rename.md. +Current build: CMakeLists.txt, cmake/VoidDependency.cmake, tests/CMakeLists.txt; +docs/roadmap/01-bootstrap-dependencies.md and26-vbs-self-build-adoption.md. +VBS references are source-only: /home/faumaray/Projects/VoidBuildSystem/include/Void/Build.hpp, +docs/SDK.md, build.cpp, recipes/VoidLibrary/VoidLibraryRecipe.cpp and +src/SelfHost/TestRegistryGen.cpp. Check current root evidence for seed readiness. +Current protocol: include/vls/{Framing,Json,Server}.hpp, src/{Framing,Json,Server,main}.cpp. +Uncommitted code: include/Void/LanguageServer/{Protocol,Documents,Workspace}/ and +src/{Protocol,Documents,Workspace}/. Tests: tests/{JsonTests,JsonCapabilities, +LifecycleTests,ProcessTests}.cpp and tests/TestSupport.hpp. Relevant dependency only as needed: +build/bootstrap/_deps/voidlibrary-src/include/Void/Data/StrictJson.hpp, +Unicode/Utf.hpp, Core/Hash.hpp and System/Path.hpp. No broad sibling scans. + +## 5. Write ownership and coordination +Write scope: none +All actors share the checkout. Root owns integration/build/docs; no active source +worker currently. Source changes require later explicit owned tasks. No Git writes, +branch switches, staging, commits, pushes, cleanup, global changes, sibling changes +or Serena project switches. Never scan credentials/env/keys/WG.conf or ignored caches. + +## 6. Implementation or investigation approach +Use exact graph project home-faumaray-Projects-VoidLanguageServer only after coverage +checks, then source verification. Current index2026-11-27 mostly matches; some headers +have partial parse ranges. Do not assume an edge or absence proves behavior. +Map existing APIs and call paths, identify semantic gaps, then propose one canonical +protocol layer and a controlled compatibility transition. Upstream StrictJson now +provides checked serialize; specify how errors propagate without fabricated data. +Review URI/position/snapshot lifetime, edits/desync recovery and disk/overlay races. +Define a native build/test/dependency path using verified VBS APIs, not a custom +action that delegates to CMake. Its Git SDK currently requires Commit{sha40}; retain +the no-pin main policy through explicit managed-source acquisition/path input, +without inventing branch APIs. Native Void::Testing registration must execute all37 +existing bodies and preserve process-executable discovery. Keep all build/dependency +outputs inside this repository's ignored trees. No VBS/Library sibling mutations. +Define trust/configuration behavior independently from actual subprocess execution. +Freeze NEW build/revision identities and cancellation/publication rules. Sequence +separate workers only after public headers and shared CMake/test ownership are clear. +Research protocol facts from primary LSP3.17 docs; ask root only for product choices. + +## 7. Interfaces and data contracts +Existing names: Void::LanguageServer::Documents::{LineIndex,DocumentIdentity, +DocumentSnapshot,DocumentStore,TextEdit}; Workspace::{WorkspaceSettings, +PartialWorkspaceSettings,TrustPolicy,ToolIdentity}; Protocol::{Json,RequestId, +parse_json,serialize_json}. TrustPolicy is declarations only, not working authority. +NEW BuildContext and AnalysisRevision must encode original provider/context/profile/ +target/toolchain/environment/source/dependency identity and immutable generations. +No flag merging across alternatives; missing native metadata remains explicit. +LSP UTF16 default/negotiated UTF8, CR/LF/CRLF, sequential edits, immutable snapshots, +oversized character clamping, invalid scalar boundaries and versioned desync recovery. +No semantic capabilities until actual semantics exist; document synchronization may +be advertised once the real handler and executable tests prove it. + +## 8. Dependencies and integration +Root retains source ownership while contracts are planned. Fresh astra_reviewer +preflight must inspect your proposed wave before implementation. Root serializes +CMake, shared schemas and final server integration. Documents/workspace can be disjoint +workers after interface agreement; build-model depends on their identities. +VBS current source has Editor CompDb/IDE query APIs but required native tooling +coverage must be assessed separately. Compiler and debugger feasibility remain gates. + +## 9. Edge cases security and performance +Root observed: temporary serializer silently nulls nonfinite numbers; line offsets +past line end currently reject instead of clamp; disk content is read outside the +store lock and may race a newly opened overlay; TrustPolicy has no implementation. +Assess these against source, not as mandated verdicts. Examine URI alias/symlink +policy, stale versions, bounded file/text growth, snapshot lifetimes, trust revocation, +execution-bearing flags and unknown configuration fields. Repository-local settings +never grant executable/plugin/wrapper authority. Plan large-file and concurrency +checks, not just happy-path unit tests; benchmark targets remain full-roadmap goals. + +## 10. Acceptance criteria +1. Requirement-to-wave map for R-003,R-006,R-007,R-008,R-009,R-011,R-021. +2. Existing implementation gaps and exact NEW/retained interfaces clearly separated. +3. Disjoint write sets and ordered integration for protocol/documents/workspace/model. +4. Failure semantics and regression scenarios for identified cross-component risks. +5. Concrete validation based on existing Void::Testing/CTest, proposed additions +clearly marked NEW; no imaginary registered suites. +6. Remaining27-part gates preserved, not reduced to bootstrap success. + +## 11. Verification commands and evidence +All commands cwd repository. Existing observed: +dev cpp-gcc -c cmake --fresh -S . -B build/bootstrap -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON +dev cpp-gcc -c cmake --build build/bootstrap --parallel 2 +dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure +All now exit0 after the root CLI fix. LastTest.log is in +build/bootstrap/Testing/Temporary. Existing test bodies are22+6+9. +Local override configure uses -DVLS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidLibrary +in build/local; root records its latest outcome in VERIFICATION.md. +Planning may use read-only source/graph queries and bounded existing test probes; +no mutations or broad rebuilds needed for this report. + +## 12. Constraints and stop conditions +Stop if the gpt-6.2-astra Max dispatch fails, if role/model access fails, or if +the requested investigation requires secrets/unowned changes. Do not substitute a +role/model or say Max was verified from a role label. Keep unsupported frontend +semantics and compiler patches as separate gates, not implied approvals. + +## 13. Authorization and decisions +User's2026-11-27 goal authorizes implementing the plans beyond the original milestone0; +later steering makes VBS primary and requires the separate branch already created. +no repeat scope approval needed for their stated scope. User also authorized continuing +from existing dirty files and explicitly rejected XHigh. Global configuration edits +are not part of this task. This persisted contract must pass tasklint and root semantic +review before dispatch; delivery is read-only advice, not permission or acceptance. + +## 14. Return format +T-PLAN-002; DONE/PARTIAL/BLOCKED; dependency/invariant map; proposed exact interfaces +and ownership; ordered implementation/test plan; severity-ranked existing risks; +sources/coverage; observed commands/results; unresolved product choices; files changed +none. Do not spawn children or message the user. diff --git a/docs/agent-workflow/tasks/T-PLAN-006.md b/docs/agent-workflow/tasks/T-PLAN-006.md new file mode 100644 index 0000000..4eb94c9 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PLAN-006.md @@ -0,0 +1,48 @@ +# Map the live VBS and compilation database provider interfaces + +Task ID: T-PLAN-006 +Role: astra_planner +Status: READY + +## 1. Context and baseline +Work read-only in /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975. The server now builds natively, advertises tested document sync and contains tested passive trust primitives. T-MODEL-005 implements the immutable common model. Root needs the next provider and workspace-session integration contracts while that model settles. GPT-6.2 Astra Max is requested. + +## 2. Objective and deliverables +Deliver a concrete source-backed implementation plan for native VBS tooling and compile_commands compatibility plus their passive session entry points. Identify reusable paths, file formats and constraints with a minimal set of fixtures. Send early concrete advice on shared file I/O and actual VBS v1 locator semantics. + +## 3. Scope and non-goals +Read-only architecture and dependency mapping for roadmaps 04–07. Read only synthetic artifacts generated by this VLS task or the indicated source files. Keep compiler/debugger/clients and actual process launch out of this package. Never turn a VBS declaration file or a compilation database into evidence of a complete resolved tooling export. + +## 4. Files to inspect +Read docs/roadmap/04-workspace-configuration-trust.md, 05-build-contexts.md, 06-native-vbs-tooling.md, 07-compilation-database.md, docs/agent-workflow/tasks/{T-TRUST-004,T-MODEL-005}.md, actual Workspace configuration/trust and RegularFile interfaces, src/main.cpp and src/Server.cpp. Native evidence: build/vbs-native-probe/query-debug.json, build/native-validation/profiles/debug/editor/status.json, .vbs/editor_selection.json and the specific generation compdb it references within build/native-validation. The committed VBS seed is build/tools/vbs-6c225-src, notably src/Editor/CompDb.cpp; current sibling /home/faumaray/Projects/VoidBuildSystem/src/Editor/CompDb.cpp is read-only for source comparison. Inspect Model.hpp only if present, use the planned API as provisional until handoff. + +## 5. Write ownership and coordination +Write scope: none +No changes to shared source, Git, generated selections/compdb, dependencies or sibling repositories. Root authors/contracts shared schemas and registers tests. The planner has no children and sends no user messages. + +## 6. Implementation or investigation approach +Determine exact v1 selection-ticket, build-root, profile-status, generation and compdb relationships, including relative paths from real outputs and effects of stale status and moved aliases. Define a passive native importer that preserves VBS provenance and unready fields. Locate evidence of any richer resolved export. If proposed rather than produced, keep a versioned fixture contract distinct from existing v1 and list evidence needed from upstream. Map compdb arguments/command quoting per the official LLVM schema and supported Linux GCC/Clang behavior, driver response-file rules, path normalization and unknown-operand outcomes. Recommend where bounded regular-file read, path authority and stable identity logic can be safely shared. Keep deterministic CPU/memory/expansion limits and file replacement semantics. Define VS Code/Neovim neutral LSP/CLI entry: workspace roots, manual provider choice, passive status and configuration invalidation. Use only genuinely scoped source inputs and avoid speculative compiler endpoints. + +## 7. Interfaces and data contracts +T-MODEL-005 design: scoped session/workspace/provider generation, multiple BuildContexts each with one owning TU and ContextKey(profile,target,role,alternative,TU), source mappings, original/analyzed argv/cwd, explicit metadata unknowns and capability-specific readiness. Model selection takes editor and explicit override. Trust classifier takes tokens, known wrappers, pinned ToolIdentity and explicit driver, but passive status must work without authority; uninspected tool is an unknown with execution denied. Keep caller and provider responsibilities explicit and avoid cross-root authority. + +## 8. Dependencies and integration +Provider writers own disjoint VBS and compdb paths after shared model freeze. Root owns shared provider bookkeeping/file I/O and protocol/workspace session or can assign separately. Identify which work can start without the other adapter, which needs provider-neutral parsing helpers, and which genuinely depends on a VBS producer outside VLS. Preserve caller-visible behavior and safe read-only fallback. + +## 9. Edge cases security and performance +Never execute compiler commands, wrappers, project descriptors, response-file content or generators while discovering. Separate declarative arguments, authority, and execution. Address relative paths/traversal/symlinks, unstable reads, stale reverse completions, opaque drivers, response-file cycles, duplicate output rows, header ownership, missing generated artifacts and last-good status. Include a bounded approach for large compdb inputs and prohibiting shell evaluation. + +## 10. Acceptance criteria +1. Exact source and observed synthetic file/field references, proven versus unavailable native metadata. 2. Explicit contract and ownership per shared helper/provider/session, with proposed new public names clearly marked. 3. Test fixtures for selection/replacement/compdb duplicate and dangerous command cases, plus one live read of our synthetic VBS generation and one actual CMake compilation database entry. 4. Return amendments needed before fresh provider preflight and any true scope-level decisions early. + +## 11. Verification commands and evidence +Use git status --short --branch, targeted git/source reads, scoped graph coverage for relied-on paths and bounded JSON extraction for synthetic fixtures. No build required. If citing standard compdb grammar, rely on the official LLVM compilation database documentation only and use public queries with no local data. Return actual operations and identified evidence gaps. + +## 12. Constraints and stop conditions +Stop before cross-repository changes, project commands/execution, accessing private settings or unrelated profiled data. Low level details absent from a published schema must be unknown; do not suggest assigning fabricated toolchain/module data. Distinguish per-provider blocker from tasks that can ship independently. + +## 13. Authorization and decisions +User authorized all plans on a separate branch, native VBS primary, VoidLibrary main, and GPT-6.2 family at Max. This source-level planning assignment precedes implementation contracts. Capability promotion or an upstream publish requires its own evidence and authorization. + +## 14. Return format +T-PLAN-006 DONE/PARTIAL/BLOCKED, exact observed data flows, contracts and failure semantics, proposed file ownership, root integration order, acceptance checks, unresolved upstream requirements and commands/evidence. No edits or user-facing messages. diff --git a/docs/agent-workflow/tasks/T-PLAN-DAP-020.md b/docs/agent-workflow/tasks/T-PLAN-DAP-020.md new file mode 100644 index 0000000..2217ead --- /dev/null +++ b/docs/agent-workflow/tasks/T-PLAN-DAP-020.md @@ -0,0 +1,48 @@ +# Map the first recorded and live debugger protocol operations to actual compiler evidence + +Task ID: T-PLAN-DAP-020 +Role: astra_planner +Status: READY + +## 1. Context and baseline +Shared branch feat/implement-roadmap ca04975. Roadmaps 17–21 require both live/replay DAP plus custom inspection. Root built local GCC 16.2 patches, standalone vls_gcc_probe leaf/supervisor and bounded journal/replay; 13 trace cases and actual step/cancel processes pass. An unmodified Nix GCC 16.2 with GDB can separately expose two nested integer constexpr returns. Neither prototype currently speaks DAP. Normal VLS stdio runs LSP. + +## 2. Objective and deliverables +Design the smallest real end-to-end first DAP + shared inspection package. Map current code and wire data to a recording session a user can inspect without a compiler, plus the first real live control integration. Identify disjoint implementable files, what can run now, exact preflight contracts and acceptance tests on an actual captured compiler trace. No release decision. + +## 3. Scope and non-goals +Read-only plan for DAP + shared session/inspection. Scope current integral returns/capabilities only. No application changes, no compiler modifications, no misleading claims for templates, constraints, full source locations or general product readiness. No calls to user or external messaging. + +## 4. Files to inspect +Inspect docs/roadmap/{17-compiler-debug-instrumentation,18-live-debugging,20-dap-service,21-inspection-api}.md and the recorded replay roadmap; experiments/frontend/gcc-worker/{Trace,Supervisor,Main,Leaf}.{hpp,cpp} as existing, tests/debug/TraceTests.cpp, tests/native/{GccLeaf,GccSupervisor}.py, tests/corpus/frontend/verify-stock-gcc-gdb.py; include/Void/LanguageServer/Protocol/{Framing,Json}.hpp; src/main.cpp, include/vls/Server.hpp, build.cpp. Use actual trace capture/replay outputs if available for the fixed fixture. Consult official Microsoft DAP specification for request/event ordering, handle lifetimes, coordinate bases, source references, paging and capability flags. + +## 5. Write ownership and coordination +Write scope: none +Use only private build/plan-dap-020 for optional neutral data/transcripts. No source edits, spawned agents, remote publication, starting an editor or shared build changes. + +## 6. Implementation or investigation approach +Trace creation/replay, sequence validation, available frame tree/name/value, authored snapshot and sourceKind, unavailable coordinates, integrity checks, seek/finish, error/truncated status and memory limits. For DAP distinguish protocol seq from compiler sequence and reference lifetime. Derive minimal client path initialize→launch→configured→stopped→threads/stack/scopes/variables/source→move→disconnect or terminate. Consider custom immutable timeline/tree payload sharing the session. Identify when to emit responses/events and handle expired refs and true source vs logical declaration. Decide whether existing replay rereads the whole mutable path per seek and propose a bounded retained immutable read/index. Avoid a second journal parser/timeline. + +## 7. Interfaces and data contracts +Suggest NEW C++ owner/types for immutable replay open/seek and DAP state, separate from a standalone stdio runner. Show exact public contract and wire field mapping; fixed recording file explicitly selected by launcher. No client-provided arbitrary filesystem reads on source requests. Scope live backend to actual supervisor stop ordinal/ack and one command authority. Explain how stock-GDB recordings could join without fabricating unsupported hook events. + +## 8. Dependencies and integration +Prior research and evaluator/trace probes allow narrow functionality pending a separate integrated review. Default projects continue using their usual compiler. Root will write/lint subsequent assignments and integrate manifests. Name independent packages that can start while stock diagnostic integration proceeds. + +## 9. Edge cases security and performance +Bound traffic, output entries, replay record source bytes, retained dictionary state, handle namespace, old/stale actions and client disconnect; don't invent blanket authentication, new external services or additional approval UX for a private stdio connection. Explicit read-only recording authority preserved. + +## 10. Acceptance criteria +Return source-confirmed initial slice, follow-ons, accepted limitations, concrete executable acceptance commands/fixtures. Distinguish actual feature from plan, through actual step/seek/source/value evidence. If DAP implicit method expectations conflict with data, show exact official basis and a truthful behavior. Options should work for both VS Code and Neovim clients in later stages. + +## 11. Verification commands and evidence +Read-only. Optional run build/native-validation/profiles/debug/out/bin/vls_gcc_probe replay on an existing explicitly named fixed-test journal in private scratch, or run build/bootstrap/tests/vls_trace_tests. Obtain wire facts from sources and targeted small outputs. Cite evidence lines and primary official documentation; don't expose source outside the approved environment. + +## 12. Constraints and stop conditions +Stop if actual files contradict the needed evidence and report which distinct capability or small change can close the gap. No staging, rich UI, general redesign, product license, alternate model or public launch. No target exploitation or reverse engineering of unrelated software. + +## 13. Authorization and decisions +User authorized all plans and D-027 GPT-6.2 Max. D-030 permits local compiler feasibility experiments. Output is a concrete graph for the approved implementation, not a new product scope decision. + +## 14. Return format +T-PLAN-DAP-020 DONE/PARTIAL with dependency order, new interfaces/owners, actual and missing trace facts, exact DAP events for fixture, minimal verification and limitations. Send ready independent packages early. diff --git a/docs/agent-workflow/tasks/T-PLAN-EDITORS-022.md b/docs/agent-workflow/tasks/T-PLAN-EDITORS-022.md new file mode 100644 index 0000000..9405fbf --- /dev/null +++ b/docs/agent-workflow/tasks/T-PLAN-EDITORS-022.md @@ -0,0 +1,48 @@ +# Plan the two editor clients against the integrated LSP and DAP services + +Task ID: T-PLAN-EDITORS-022 +Role: astra_planner +Status: READY + +## 1. Context and baseline +The shared VoidLanguageServer repo is on feat/implement-roadmap at ca04975 with uncommitted integration. Stock diagnostics and passive build metadata operate over LSP. A real C++ replay adapter and /v1 inspection API run over DAP. tests/native/NeovimReplay.lua already drove an actual nvim-dap session with nested values 17/34, pages and source bytes in Neovim 0.12.6. The installed code reports 1.147.0, commit 8a14f0cc1b08d531eb83255ea3764ae22aa932b5. No client packages exist. Live, full source mapping, guarded rename, indexing and broader backend semantics remain independent. + +## 2. Objective and deliverables +Plan two independently implementable thin client packages for VS Code and Neovim, using the actual LSP and replay DAP in normal editor entry points. Resolve test dependencies and issue precise implementer/preflight interface advice. Keep full client roadmap acceptance with separate remaining live/semantic/transaction gates. + +## 3. Scope and non-goals +Client startup/config, passive provider status, opt-in stock diagnostics, user-selected offline replay, read-only bounded timeline/frames/sources, stale callback rejection, disconnect cleanup, real headless/extension-host proof. No distribution, source edits, UI unrelated to debugger/IDE, or extra servers. Avoid implementing user-space semantic features in Lua/TypeScript. + +## 4. Files to inspect +Read docs/roadmap/22-vscode-client.md and docs/roadmap/23-neovim-client.md, tests/native/{NeovimReplay.lua,DapReplay.py,StockDiagnostics.py}, src/debug/dap/{Main.cpp,Projection.cpp}, src/debug/inspection/ReplaySession.cpp, src/main.cpp, src/Server.cpp, README.md. Consult current official Neovim 0.12.6 and nvim-dap docs and VS Code Language/Debug extension APIs. build/dap-evidence/nvim-dap is the isolated upstream checkout cfa2d58f4537aca6ca83e2de1a0d9f1491121264. The reference DAP source is one capture; frame locations are logical only. + +## 5. Write ownership and coordination +Write scope: none +Private benign probes under build/plan-editors-022 are allowed. No edits to clients, tests, user configuration, VS Code profile, manifests, shared state or Git. Other agents share the checkout. Do not install plugins into users' environments or attach to existing editors. A test extension host must have disposable user-data and extensions directories and exit cleanly. + +## 6. Implementation or investigation approach +Map the actual client command flow: user config selects installed binary and root, normal edit sends incremental notifications and receives stock diagnostics, status exposes selected build context. Dynamic adapter launches explicit absolute file selected in the current client action; one session and generation binds custom page/view replies. Request standard stored source by reference rather than reopening client-provided paths. Find available immutable/testable dependencies for TypeScript, vscode-languageclient and an actual VS Code host without changing user configs. Check current accessibility of a disposable display session or extension-host testing options. For Neovim prefer native LSP and optional nvim-dap instead of a new protocol client. Use editor APIs for scratch text and generation checks with captured session plus current subscription. Avoid script execution when rendering data. + +## 7. Interfaces and data contracts +Existing LSP init, sync, voidLanguageServer/providerStatus, analysisStatus; CLI vls --stdio and launcher-only --workspace-root/--gcc-profile for stock diagnostics. Existing vls-dap --replay ABSOLUTE_TRACE, schemaVersion/sessionId/generation and vls/session,timeline,frames,seek; standard loadedSources/source. Only client-initiated user actions can choose a journal or process. No native HWND/platform UI, no separate network channel. Missing capabilities or peers should keep remaining functionality usable. + +## 8. Dependencies and integration +Root owns build registration, shared API docs, release and actual integration. Client authors get disjoint clients/vscode/ and clients/neovim/. Normal tests cannot fetch tooling or install into external workspaces. Keep test-only opt-in or explicit dependency locator for externally installed editor and nvim-dap. Identify separate code/test packages so one editor can run if the other is unavailable. + +## 9. Edge cases security and performance +Document unavailable process, known reference, multi-root scoping, executable configuration origin/trust, presence of a similarly named executable under workspace, omitted vs repeated settings, failed callbacks after stop/seek/disconnect switching/replaced buffers. Avoid duplicate clients, clearing third-party mappings/config/session listeners, opening an external debuggee or read-only generated content as a workspace file. Test source/data escaping, editor session shutdown and no stale content after switching editor sessions. + +## 10. Acceptance criteria +1. Source/API-confirmed normal LSP and DAP client path in each actual editor. 2. Chosen package/tool versions and reproducible real acceptance commands with optional development prerequisites. 3. Thin view schema, controls and error state without fabricated backend coverage. 4. Minimal initial deliverables, exact ownership, UX and lifecycle differentiating tests; retain later rename/live gates. + +## 11. Verification commands and evidence +From root run nvim --version and code --version; do not activate normal user startup scripts. Inspect nvim-dap's checked commit with git -C build/dap-evidence/nvim-dap rev-parse HEAD. Read the existing headless test. If privately verifying VS Code, use the installed code executable, explicit user-data-dir, extensions-dir, locally created test fixture and process deadline; do not reuse a running editor profile. No account interaction or extension marketplace publication. + +## 12. Constraints and stop conditions +Do not stage, commit, release, install global tools or open arbitrary projects. Report missing compatibility evidence instead of relying on screenshots or sample responses. Read only relevant code; no environment secret/config inspection. Do not ask the user or spawn additional agents. + +## 13. Authorization and decisions +Full approved roadmap D-022, primary VBS D-025, authorized generic GPT-6.2 Astra at Max D-027/029. Current mode is local development; publishing extensions and project license are deferred. + +## 14. Return format +T-PLAN-EDITORS-022 DONE/PARTIAL. Return verified versions/commands, two ownership-ready contracts, missing proof and acceptance cases. Send an early independent slice when ready. diff --git a/docs/agent-workflow/tasks/T-PLAN-GCC-008.md b/docs/agent-workflow/tasks/T-PLAN-GCC-008.md new file mode 100644 index 0000000..9d0df19 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PLAN-GCC-008.md @@ -0,0 +1,48 @@ +# Design the isolated GCC 16 worker and evaluator hooks + +Task ID: T-PLAN-GCC-008 +Role: astra_planner +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975, dirty files authorized. Primary native descriptor build.cpp, optional CMake verification, VoidLibrary main 7d7d23e. T-PLAN-006 verified VBS 6c225c2 selector/status/generations and actual compdb rows. Build/Model.hpp, Workspace/{Configuration,Trust}.hpp and Protocol/Json.hpp are implemented. Root owns build/test registration, CLI, session, docs and integration. No shared tree branch switches, Git mutations, sibling writes, child agents or independent user messages. User D-030 now expressly authorizes local versioned GCC 16.2 instrumentation and an isolated prototype worker; distribution and project license deferred. + +## 2. Objective and deliverables +Provide source-grounded, implementable contracts for the first compiler-backed IDE operations and a genuine event-time debugger. Map an initial vertical slice and follow-on work across 08/09/12/17/18/19 before compiler patch implementation. + +## 3. Scope and non-goals +Read-only planning. No compiler source modifications, API implementation, agent children, external disclosure or dependency changes. Derive from actual GCC 16.2 code and feasible bounded declarations. Do not resurrect Clang-only path or produce fake semantic data. + +## 4. Files to inspect +Read tests/corpus/frontend/gcc-{evaluation,queries}.cpp, probe-gcc-tooling.py, docs/roadmap/{08,09,12,17,18,19}* and Build/Model.hpp. Official source: verified checksum extract build/gcc-gate/gcc-16.2.0/gcc/cp/{constexpr,constraint,pt,reflect,decl,parser,semantics}.cc and gcc/{plugin.def,input.h}. Probe logs under build/gcc-gate (declarations.sarif,queries.original,tooling-report.json,live-stop.log). VoidLibrary generated include/Void/System/Process.hpp for bounded live stdout/stdin/stderr; do not inspect ambient user files. + +## 5. Write ownership and coordination +Write scope: none +Root owns compiler source download/config/build and the future versioned patch integration; you only plan fields, hook points, owner boundaries and stop conditions. + +## 6. Implementation or investigation approach +Inspect real semantic resolution/decl use, evaluator call-entry/exit, constraint accept/failure, nested instantiation, reflection query/splice/expansion hooks. Determine availability of exact source location/macro/spelling/origin, event-time typed value and nested causality. Separate paths requiring hooks from already proven diagnostics. Plan disabled fast path, private trace/control descriptors, bounded input, fixture filters, public client-worker protocol covering cancellation/reaping and trace loss. Consider Nix GCC driver uses same libstdc++ and effective include path; private cc1plus/build driver must prove corpus equivalence. Recommend how to send real AST identity for declaration/use without retaining tree pointers beyond compiler lifetime. Send early small NEW hook contract with exact symbols and test distinguishing real return values from final static_assert. + +## 7. Interfaces and data contracts +One worker owns cc1 state; inspector results reference session/request/source snapshot/compiler identity. Capture typed, bounded copies at event time, sequence and causal parent, physical+logical/spelling origin; unsupported/optimized-away explicit. Isolated prototype explicit opt-in for fixed workspace-owned fixtures only, with real values (e.g. 17/34), resuming/stepping must control live process. Hooks measured disabled/enabled. No arbitrary plugin selection from metadata. No requirement to decide a global license to build this local GCC patch. + +## 8. Dependencies and integration +This planner does not own provider preflight or normal CLI. Root runs stock source build in parallel; production compiler launch remains gated by actual scoped command and trusted worker, not D-030 alone. Derive disjoint actual files for compiler patch/export and worker with common DTOs owner. + +## 9. Edge cases security and performance +Material risks include recursion during pretty printing, GC lifecycle, early returns/cached calls/error unwinding, exception/failure/abort, implicit functions/builtins, nested constraints/compiler Sema re-entry, pipe backpressure and malformed control, terminal state on kill and unbounded header evidence. Live stop watchdog must distinguish stopped/running and permit process group cancellation. + +## 10. Acceptance criteria +1. Exact source symbols/locations for early narrow hooks and future interfaces; 2. Scoped data contract and disjoint ownership, 3. concrete passing/failing constexpr fixtures and tests for event-time values + stop/cancel; 4. sources/commands for a real IDE lookup/invalid edit and a debugger witness; state compiler limitations explicitly. 5. No general LICENSE decision or production claim. + +## 11. Verification commands and evidence +Use git status --short --branch, scoped code graph coverage on VLS sources, direct GCC release reads and existing probe logs. No GCC rebuild/second copy or expensive compilation necessary. Read GNU plugin and diagnostic docs only when needed; exact local release primary source is authoritative. + +## 12. Constraints and stop conditions +Report early any hook unable to produce source or values and propose next genuine alternative within the approved local experiment; ask root before scope expansion. Stop after mapping useful code, no generic exhaustive narrative. + +## 13. Authorization and decisions +User selected GCC16 evaluation and explicitly approved a local worker and versioned hooks. Requested GPT-6.2 Astra Max. Planner meets mandatory dependency/risk gate for this substantial new change. + +## 14. Return format +T-PLAN-GCC-008 DONE/PARTIAL/BLOCKED, early implementation-ready slice, exact source anchors, field/control/liveness model, executable fixtures/acceptance and unresolved questions. diff --git a/docs/agent-workflow/tasks/T-PLAN-SEMANTICS-010.md b/docs/agent-workflow/tasks/T-PLAN-SEMANTICS-010.md new file mode 100644 index 0000000..a82c882 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PLAN-SEMANTICS-010.md @@ -0,0 +1,49 @@ +# Plan the first editor-facing semantic worker against real Void contexts + +Task ID: T-PLAN-SEMANTICS-010 +Role: astra_planner +Status: READY + +## 1. Context and baseline +Shared VoidLanguageServer feat/implement-roadmap ca04975. Primary VBS and optional compile_commands providers now return real contexts from installed stdio server (native36, compatibility58). Reviewer identified alias/grant issues under repair. GCC16.2 private reference parity: 19 language, 8 tooling, 33 module checks. Versioned 0001 returns real eval evidence, 0002 v1 produces typed calls and explicit fields with witnessed definitions and valid source ranges. tests/corpus/frontend/verify-gcc-ide.py exercises direct overload edits, duplicates, macro/line and Unicode. D-028/D-030 authorized evaluation and a local compiler prototype; production backend selection and license remain open. + +## 2. Objective and deliverables +On resumption the stock GCC 16.2 fixture now also passes both edited live return pairs with GDB (tests/corpus/frontend/verify-stock-gcc-gdb.py). Use stock compiler capabilities where evidence supports them. This observation does not settle full debugger/compiler choice. Prior planner assignment returned HTTP 429 before findings. Send a concrete module/dependency slice early so implementation can start independently. +Build a concrete, gated plan for a usable compiler-backed editor path: dispatcher/worker, immutable overlays, module ownership, diagnostics/navigation and latency scheduling with real data. Separate work already within the local prototype approval from the remaining explicit product/backend decision. Identify minimum meaningful user-facing integration and the evidence which would justify selection or rejection. + +## 3. Scope and non-goals +Read-only architecture, source evidence and precise independent implementation packages. No implementation, papers in place of actual local APIs, editor protocol advertisement, user messages or unreviewed compiler changes. + +## 4. Files to inspect +Inspect docs/roadmap/{08-frontend-feasibility,09-semantic-workers,10-*,11-cpp-modules,12-reflection-provenance,13-diagnostics-recovery,14-completion-hover,15-index-persistence,16-navigation-rename}.md, docs/agent-workflow/DECISIONS.md, actual include/Void/LanguageServer/{Build/{Model,Providers},Documents/{DocumentStore,DocumentSnapshot},Workspace/Trust}.hpp, include/vls/{Server,WorkspaceSession}.hpp, src/{Server,WorkspaceSession}.cpp, src/Build/{Model,VbsProvider,CommandImport}.cpp, experiments/frontend/gcc-worker, compiler patches 0001/0002, tests/corpus/{modules,frontend}, actual selection and real main.cpp native/context row. Review GCC libcpp locations needed; no shared builds/indexer reconfiguration. + +## 5. Write ownership and coordination +Write scope: none +Read-only. If a targeted script is necessary use only private ignored build/plan-semantics-010. No shared source, docs/branch/staging/commits, sibling edits or child agents. + +## 6. Implementation or investigation approach +Trace current stdio single-threaded read/dispatch, document snapshots/epoch, selection status (generations may be ephemeral), model AnalysisRevision/PublicationSlot, scope grants/compiler classifier, patch record coverage and physical proof. Identify concrete missing data gates and how to materialize immutable overlays for both owning TU and headers/importers without executing project descriptors, arbitrary flags or generators. Favor actual compiler APIs, context-specific dependency evidence and real fixture/production Void inputs. Consider first frontend diagnostics and positive hover/go-to-definition/completion using same worker when safe. Account for ordinary clients relying on untrusted metadata and explicit trusted backend/toolchain identity. Determine how backend-neutral module worker/graph scheduler can proceed independently if a future production backend decision is required. + +## 7. Interfaces and data contracts +Propose NEW exact APIs/types/paths and integration points with existing ones. Bind async completion to configuration/trust/document/context/dependency generations with one serialized publication guard, LSP cancellation/id handling plus concurrent document notifications; requests should not block input. Report constraints for wire acceptance, SourceMapping, template/reflection facts and diagnostics coordinate conversion using SARIF display units. For modules inspect actual P1689r5 topology and CMI result formats: model compiler-specific build identity, immutable artifact lease, private caches, honest missing/generated readiness and dynamic unsaved imports. + +## 8. Dependencies and integration +Parallel architecture only. Root owns operational supervisor/trace and compiler integration. Other agents own trace and provider remediation. Do not wait on them or ask to change ownership: plan against known public shape and clearly identify uncertainties. Provide first actionable disjoint slice early for an independent preflight reviewer. + +## 9. Edge cases security and performance +Respect file/root tool authorization, loss of source provenance on macros/#line or system headers, caps on concurrent frontend work/trace/bytes, null vs real empty results, stale publication fencing incl no-op state, symlink races, immutable revisions, no false capability advertisements. Avoid restricting the plan to the existing two types/roles or a one-file demo. + +## 10. Acceptance criteria +Deliver evidence-based packages and distinguishing acceptance cases (at least one actual Void header/TU, real multi-file module/overlay, same spelling different overload, invalid edit then recovery, stale result, cancellation and responsive progress). State what current gate actually proves and what facts/user decision are still necessary. Identify steps root can implement immediately under D-030. + +## 11. Verification commands and evidence +Use git status --short --branch, scoped graph coverage then actual file evidence, read GCC/headers and active database as needed. Read the completed logs build/gcc-gate/{observed-ide,observed-events,private-reference,private-modules}.log and build/native-evidence/providers-installed.log. No full compile/runs needed. Record actual commands and exits for any probes. + +## 12. Constraints and stop conditions +Stop for unresolved product decision or missing data, but continue other independent contracts and explain the exact boundary; do not silently choose the production engine or defer all useful work. No new project licensing decision or backend dependency installation. + +## 13. Authorization and decisions +Approved full roadmap and private compiler evaluation (D-022/028/030). GPT-6.2 Astra at Max planning assignment. User asked all agents to use Max. Root retains integration and user interaction. + +## 14. Return format +T-PLAN-SEMANTICS-010 DONE/PARTIAL, concrete dependency graph/symbols, first disjoint scoped WHAT/HOW, proposed owner contracts and compiler/software evidence, gates/decisions. Send early when first actionable for preflight. diff --git a/docs/agent-workflow/tasks/T-PLAN-STOCK-NAVIGATION-014.md b/docs/agent-workflow/tasks/T-PLAN-STOCK-NAVIGATION-014.md new file mode 100644 index 0000000..1cc45d0 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PLAN-STOCK-NAVIGATION-014.md @@ -0,0 +1,48 @@ +# Prove semantic navigation with the ordinary project compiler + +Task ID: T-PLAN-STOCK-NAVIGATION-014 +Role: astra_planner +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975 plus local edits. Normal editor diagnostics use stock GCC 16.2 through an opt-in sealed frontend profile. The private compiler IDE hook resolves a closed int/double fixture but gives no occurrences in the real Void DocumentSnapshot.cpp. Earlier T-PLAN-SEMANTICS-010 proved the stock compiler resolves the two actual Void::Hash::fnv1a64 overloads after editing argument text, with controlled diagnostic tagging. Stock GCC/GDB was also tried for constexpr inspection. Native build metadata and disk/overlay views already exist. + +## 2. Objective and deliverables +Investigate a concrete route to compiler-proven hover and definition with an unmodified installed GCC 16.2. Try a separate, explicitly application-owned GCC plugin against the actual stock package if headers/ABI available. Produce an executable counterexample or proof on terminal call-token attribution, selected declaration/definition, canonical type, file provenance and manual overload edit. Recommend the next implementable ownership packages and honest limitations. The roadmap requires normal editor entry points after the evidence, not a benchmark-only static index. + +## 3. Scope and non-goals +Use closed benign in-memory or private local fixtures then a private checked copy of the existing real source. Preserve production profile and host compiler; no compiler patch or install. A workspace database may never select a plugin. No new stock plugin approval policy or arbitrary plugin loading. + +## 4. Files to inspect +Read src/Documents/DocumentSnapshot.cpp, prepared build/voidlibrary/current/include/Void/Core/Hash.hpp, tests/corpus/frontend/gcc-queries.cpp, existing compiler-patches/gcc-16.2.0/0002-ide-occurrences.patch and 0003 if present, include/vls/semantic/StockCompiler.hpp and src/semantic/{StockCompiler.cpp,EditorDiagnostics.cpp}, docs/roadmap/{08-frontend-feasibility,14-completion-hover}.md (verify actual paths). Check stock GCC's installed plugin include directory and callback declarations. Only look at named source files in the private GCC checkout for evidence, not unrelated targets. + +## 5. Write ownership and coordination +Write scope: none +Private probe sources and artifacts only in build/plan-stock-navigation-014. No new tracked sources, patches, manifests, Git mutations, shared compilation or shared caches. Other agents own their tasks. Root integrates real interfaces and any subsequent changes. + +## 6. Implementation or investigation approach +Use dev cpp-gcc to locate g++ and g++ -print-file-name=plugin, inspect available headers and stock version. A private ordinary GCC plugin may register PLUGIN_PRE_GENERICIZE or FINISH_PARSE_FUNCTION if the ABI supports it. Exercise the AST for two same-spelling calls at different physical tokens choosing distinct overloads; capture exact byte endpoints, observed declaration/type or explicit gaps. Check if location is the opening parenthesis or entire expression, if physical spelling can be proved using private source bytes and compiler evidence, if origin is a declaration-only target or real definition. Capture at least one real executable result or a concrete compiler/API evidence blocker. Avoid synthetic reflection semantics and source-lexical overload guessing. + +## 7. Interfaces and data contracts +Any proposed occurrence facts must bind to TU, source snapshot, lookup closure, generation and toolchain identity, both physical source ranges and target origin. Distinguish declaration from observed definition and unknown macro/remap cases. Report stock capability and patch-dependent capabilities separately. Generated/private plugin ABI can be version-limited and installed with VLS only in a later authorized packaging task. + +## 8. Dependencies and integration +Root can provide the current comparison compiler worker and existing replay adapter runs separately. Reuse existing closed view and approved profile for proposed worker integration; it has no provision for arbitrarily supplied GCC plugins. Avoid changing the application while proving the ordinary compiler route. The original project distributes no custom compiler or license yet. + +## 9. Edge cases security and performance +Probe same-name declarations/overloads, macro spelling, tabs/Unicode, primary file vs headers, declaration-only and malformed edit, active and stale views as appropriate. A true AST type and resolved UID do not prove a specific physical use or definition. Bound any output to selected project sources and one local compiler; no external upload or untrusted project/tool execution. + +## 10. Acceptance criteria +1. Stock binary/version/ABI and evidence of which callback facts it exposes. 2. Real overload selection/edit and trustworthy or explicitly missing use/target/type facts on stock. 3. Address applicability to real C++26 Void headers and normal entry points. 4. Return the smallest genuinely compiler-backed milestone for hover/definition, a concrete implementation/test graph, a fallback when any input is unproven, and the approval implications if any. + +## 11. Verification commands and evidence +Use dev cpp-gcc -c g++ --version and dev cpp-gcc -c g++ -print-file-name=plugin. Compile only a task-owned plugin and benign task-owned fixture under the private path, with absolute paths and bounded output. Run the unchanged project compiler on the original and edited fixture. Compare with tests/corpus/frontend/gcc-queries.cpp and T-PLAN-SEMANTICS-010 and retain exact commands/exit codes. No blanket rebuild of stock GCC, no plugin from workspace flags. + +## 12. Constraints and stop conditions +Report missing plugin headers or incompatible library as evidence and inspect whether matching headers already exist in the private prepared build. Never patch installed files, probe a third-party service, escalate or contact the user. No workspace licenses/distribution changes. + +## 13. Authorization and decisions +The full roadmap is approved D-022. Primary VBS D-025. The user wants regular-compiler compatibility and approved local backend evaluation; use GPT-6.2 Astra Max per D-027/029. D-030 licenses no distribution. + +## 14. Return format +T-PLAN-STOCK-NAVIGATION-014 DONE/PARTIAL, commands, actual compiler facts, failed routes, proposed reviewed packages, dependencies/risks and next acceptance steps. Send the first real matched occurrence early. No subagents. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-004.md b/docs/agent-workflow/tasks/T-PREFLIGHT-004.md new file mode 100644 index 0000000..4a72a5e --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-004.md @@ -0,0 +1,114 @@ +# Check native build and document foundation contracts before integration + +Task ID: T-PREFLIGHT-004 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +/home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975, with existing untracked Protocol/Documents/Workspace files and a small CLI repair. GPT-6.2 Astra at Max under D-027. Scope derives from roadmap 01/02/03/04/05/26. Planner T-PLAN-002 provides the dependency/invariant map appended to this assignment before dispatch. + +## 2. Objective and deliverables +Read-only preflight of proposed native build, document, trust, protocol and build identity contracts. Return separate immediate verdicts per slice. Identify contradictions that prevent a worker from implementing the actual scope or undermine the next consumer. Provide precise corrections. + +## 3. Scope and non-goals +Contract preflight for the next independently owned packages. The bootstrap numeric review T-REVIEW-003 found real precision/range issues. Preserve the upstream JSON contract and surface any prerequisite separately. Final diff review and compiler gate 08 are separate stages. + +## 4. Files to inspect +Read docs/agent-workflow/tasks/T-{PLAN-002,NATIVE-001,DOCS-003,TRUST-004}.md, docs/roadmap/{01-bootstrap-dependencies,02-lsp-protocol-lifecycle,03-documents-positions,04-workspace-configuration-trust,05-build-contexts,26-vbs-self-build-adoption}.md, the actual headers in include/Void/LanguageServer/{Protocol,Documents,Workspace}, their sources and existing src/{Server,main}.cpp, tests/{TestSupport.hpp,Registration.cmake}. See current native seed build/tools/vbs-6c225-{src,bin} and evidence in VERIFICATION.md. + +## 5. Write ownership and coordination +Write scope: none +Shared checkout, no edits or branch changes, no writes to dependencies, global config or generated metadata. Root owns docs, integration and fixtures. There is no need to execute arbitrary repository inputs. No children or messages to the user. + +## 6. Implementation or investigation approach +Inspect actual interfaces and the planner's proposed evolution. Check native dependency source preparation, clean/offline/update behavior, lock/selection files, the CMake trap, same-profile child executable and registration. Check LSP negotiation, positional boundaries, nonmonotonic versions, malformed known-document payloads, atomic edits/recovery, URI aliases, overlay/disk races, memory budgets. Review configuration provenance, path validation, revocation, tool identity and trust-generation boundaries. Check proposed BuildContext/AnalysisRevision for missing provenance, invalidation or stale publication. A blocking defect in one slice should have a bounded scope. + +## 7. Interfaces and data contracts +VBS 6c225c2 supplies ordinary Project targets, path/native_builder and CLI test/install. A native Void::Testing macro probe passed using Configuration, Data, Unicode, System, Testing. Existing LSP server currently advertises empty capabilities. New sync needs actual handlers, immutable snapshots and observable session tests. Cross-component revision should carry document, provider/generation, header/dependency, backend and trust identities. Never expose capabilities before wires and tests exist. + +## 8. Dependencies and integration +Root will dispatch only accepted independent slices and serialize shared headers/build/test wiring. Final review uses a fresh reviewer. Check the original user choices D-021 through D-027. These decisions supersede historical bootstrap-only and XHigh notes. + +## 9. Edge cases security and performance +Inspect boundedness of text operations/representation, cache and tool provenance, repeated/failed acquisition and no implicit project command execution. Distinguish permission to read metadata from process invocation. Reject stale/partial results and ambiguous authoritative identities. + +## 10. Acceptance criteria +1. READY/CHANGES_REQUIRED/INSUFFICIENT_EVIDENCE per immediate slice. +2. Reproducible or reasoned failure scenarios with specific contract amendments and verification hooks. +3. Disjoint ownership and dependency order including which tasks may start immediately after root disposition. +4. Identify any dependent decision that is genuinely required from the user. + +## 11. Verification commands and evidence +Use read-only git status --short --branch, git diff ca04975 -- src/main.cpp, source reads and scoped graph coverage. Root observed CTest 4/4 entries, 37 bodies and two clean native probes. Existing probe binaries and artifacts are in build/vbs-native-probe and build/vbs-framework-probe. No rebuild is required for a contract review. + +## 12. Constraints and stop conditions +Stop before scope expansion or unauthorized changes. Do not request pre-implementation proof that only the implementation can supply. Distinguish an upstream blocker from independently actionable work. Return the native-only verdict early if other slices take longer. + +## 13. Authorization and decisions +Full roadmap authorized. User explicitly prioritizes primary VBS, separate branch and GPT-6.2 family at Max for all assignments. Planning, preflight, integrated tests and fresh final review remain mandatory. Root handles disposition. + +## 14. Return format +Return T-PREFLIGHT-004 with a per-slice verdict, P0-P3 findings, exact locations/triggers/remediation/tests, ownership and unresolved prerequisites; no files changed. Do not spawn children. + +### T-PLAN-002 output for preflight and root decisions + +The planner verified the source and recommends native parity, checked protocol +consolidation, independent document and workspace owners, then LSP synchronization +and the context/revision model. Providers 06/07 follow model freeze. + +* Native: atomically prepare a usable generation of upstream main in build/, + retain the old one on failure, and capture its resolved path per build. + Keep CMake out of every VLS action. Use real native targets and VOID_TEST. + Preserve names and discover the running test's sibling vls without PATH/cwd. + Inspect project-side VBS state and preserve pre-existing compdb/links. + Root added two ordinary regressions to JsonCapabilities after T-REVIEW-003, + for 39 cases. The original 37 should still pass. Report upstream failures + from these two in both builds and retain their nonzero exit. +* Protocol: one canonical Protocol facade with legacy vls forwarding. Use + checked StrictJson::serialize, retain maximum header/body/depth limits, + propagate encoding failure before framing. The exact-ID/range gate requires + upstream numeric provenance (R-003). Read-only APIs cannot recover it from + a rounded double. Do not widen this prerequisite to block native or documents. +* Documents: scope URI bindings to an open incarnation. Keep physical paths + separate from client URIs. Ambiguous path-only overlays cannot be authoritative. + Changes/close still identify the open URI after a symlink retarget. Track the + highest observed version independently of last applied; require a newer full + replacement or balanced close/open after desync. Recheck overlays after disk + I/O (including errors and open/close ABA). Read regular files with a bound. + Session encoding is fixed; character beyond line clamps, impossible lines and + split characters fail. Expose optional disk client version and explicit origin. + Root proposes 16 MiB per document, 128 MiB shared snapshot/index admission, + 4096 open docs and 4096 changes per notification. Return typed refusal at limits + and measure memory for edits. Pin old snapshot references until released. +* Workspace: launcher explicitly selects an absolute user configuration; no + autodiscovered repository file can grant trust. Permission kinds distinguish + passive read, metadata refresh, compiler use and one explicit project action. + Bind selected spelling, canonical file, digest and generation. Revalidate a + pinned identity before a real launch in its future owner. Release locks before + callbacks. Relative paths resolve against the owning configuration, and + workspace resource preferences cannot increase runtime ceilings. +* Session: a single DocumentStore serves initialized-session notifications. + Advertise just openClose, incremental change and negotiated positionEncoding. + Default to UTF-16 and select the first supported offered encoding. Validate + signed LSP integers and complete notification arrays before applying. Known-URI + failed changes desynchronize. Report bounded stderr diagnostics with silent + notifications. Require a real subprocess transcript where ignoring edits fails. +* Model: BuildContext retains workspace/provider/immutable generation, profile, + target/alternative, host vs target role, original & semantic argv/cwd, compiler/ + stdlib/env identities, source mappings, readiness/retention and unknowns. + ContextSelection preserves alternatives and monotonic revision including A-B-A. + AnalysisRevision includes workspace/session, document identity/incarnation, + version/content/revision, context, provider/selection/config/trust generations, + backend and transitive inputs. A publication gate compares and commits atomically + and refuses cancelled/stale/incomplete work. Test identical-text reopen, stale + selection/revocation, changed imports and competing header contexts. + +### Review of the amended session and model contracts + +The initial verdict accepted native preparation, protocol, documents and trust. +Review only the corrections in T-SESSION-003 and T-MODEL-005, supplied in full. +Validate stable disk versus overlay equality, owning TU, negative lookup evidence, +operation-specific readiness and atomic publication. For the session check LSP +integer bounds, absent versus null ranges, a failed late change and the +observable astral edit transcript. Return READY or a specific remaining +blocking amendment for each. This is a continuation of the read-only review. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-007.md b/docs/agent-workflow/tasks/T-PREFLIGHT-007.md new file mode 100644 index 0000000..4235356 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-007.md @@ -0,0 +1,48 @@ +# Review the provider acquisition and publication contracts + +Task ID: T-PREFLIGHT-007 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975, dirty files authorized. Primary native descriptor build.cpp, optional CMake verification, VoidLibrary main 7d7d23e. T-PLAN-006 verified VBS 6c225c2 selector/status/generations and actual compdb rows. Build/Model.hpp, Workspace/{Configuration,Trust}.hpp and Protocol/Json.hpp are implemented. Root owns build/test registration, CLI, session, docs and integration. No shared tree branch switches, Git mutations, sibling writes, child agents or independent user messages. + +## 2. Objective and deliverables +Give independent pre-implementation verdicts for T-PROVIDER-IO-007, T-PROVIDER-ROWS-007, T-PROVIDER-VBS-006 and root T-PROVIDER-SESSION-007. Return decisive amendments early so unaffected workers can begin. + +## 3. Scope and non-goals +Technical architecture preflight only. No source changes, activities against other software or external messages. Review against actual local data and interfaces. + +## 4. Files to inspect +Read all four named task specs in docs/agent-workflow/tasks/, roadmaps 04-07, current Build/Model.hpp, Workspace/{Configuration,Trust}.hpp, Scope helper include/Void/LanguageServer/Support/RegularFile.hpp, Protocol/Json.hpp, src/Server.cpp and src/main.cpp. Read the VLS-owned .vbs/editor_selection.json, build/native-validation/profiles/debug/editor/status.json and exact selected VLS-generated compdb. Read committed VBS seed build/tools/vbs-6c225-src/src/Editor/CompDb.cpp and real VLS-CMake build/bootstrap/compile_commands.json. No sibling writes, arbitrary project files or ambient settings. + +## 5. Write ownership and coordination +Write scope: none +Root and eligible workers share this checkout. Return observations by internal message or final only. + +## 6. Implementation or investigation approach +Compare field types, purpose admission and revalidation to producer rules and sources, file symlink/rename rules and logical bases, row bounds, argv/response parsing and stable duplicate identity. Review immutable generation consistency, fresh/stale observation and fallback semantics, router path/trust/provenance and grants per root. Identify a specific distinguishing test for each material finding. Distinguish fixable current contracts from future native export and production-analysis prerequisites. + +## 7. Interfaces and data contracts +NEW namespace Void::LanguageServer::Build. Root owns Providers.hpp. ProviderScope contains WorkspaceIdentity workspace, optional absolute exact_database, exact_selector, build_root, producer_cwd (root-bound launcher grants only) and Workspace::ResourceLimitsConfig limits. enum FilePurpose {selection,status,database,response}; read_provider_file(scope,path,purpose,byte_limit) returns expected; provider_file_current(scope,file) revalidates identity. ProviderFile has purpose, logical_path, canonical_path, bytes, content_id, stamp; stamp binds admission root, opened object and selected name. ProviderIssue has string code,message and filesystem::path path. DatabaseInput has const ProviderScope& scope, const ProviderFile& database, optional profile, optional driver; DriverInput holds a workspace/purpose/generation checked Workspace::ToolCheck and Workspace::CompilerDriver, plus known wrapper spellings. import_commands(const DatabaseInput&) returns expected; ImportedCommands has vector contexts, vector dependencies and string revision. ProviderObservation has string provider, optional selection_ticket, optional profile, Generation generation, vector issues and vector inputs; fresh is a generation without blocking issues (row limitations stay in context). observe_vbs(scope, selector_path, optional), observe_compdb(scope, database_path, optional) return ProviderObservation. Root owns latest sequenced publication and revalidation at install. All reads are passive. Concrete spelling in forthcoming header coordinated by root after preflight. + +## 8. Dependencies and integration +T-PLAN-006 is the independent planner baseline. The three implementation workers wait for your per-slice verdict; root can continue the unrelated GCC/earlier-foundation work. Send first implementation-ready slice(s) promptly. + +## 9. Edge cases security and performance +Check equal-ticket generation replacement or reverse completion, selection ABA/root reincarnation, metadata vs actual execution, external exact file symlink admission, fixed byte/row/memory bounds and roots with shared configuration. Check for accidental privilege via driver input, compiler source outside root or fallback aliases. Never execute metadata or real compiler commands for this review. + +## 10. Acceptance criteria +Per-package READY or CHANGES_REQUIRED; severity, exact path/field/contract, concrete change and test. Do not prescribe unrelated features or require unavailable VBS-native rich output for today's passive observer. + +## 11. Verification commands and evidence +Use git status --short --branch, scoped graph/check_index_coverage and targeted file reads, bounded fixture data comparisons. No build necessary. Cite file lines for consequential claims and distinguish observed cases from proposed tests. + +## 12. Constraints and stop conditions +Stop for missing producer details outside allowed read data and report narrowly; do not propose broader authority. No code edits, agent children or direct user contact. + +## 13. Authorization and decisions +User approved all plans, 6.2 family and Max effort. This independent Astra review is routed through the generic role as approved in D-027. + +## 14. Return format +T-PREFLIGHT-007 verdicts, amendments, evidence, test cases and any actual blocker. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-CATALOG-009.md b/docs/agent-workflow/tasks/T-PREFLIGHT-CATALOG-009.md new file mode 100644 index 0000000..dc9a906 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-CATALOG-009.md @@ -0,0 +1,48 @@ +# Verify input identities at the source catalog and document store boundary + +Task ID: T-PREFLIGHT-CATALOG-009 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +T-PLAN-SEMANTICS-010 and the recently cleared T-SOURCE-OVERLAYS-009 define a stock GCC diagnostic input path. Root has a real closed-fixture private compiler view. T-SOURCE-CATALOG-009 proposes capturing exact observed sources and lookup names for that view. + +## 2. Objective and deliverables +Preflight the proposed catalog package for correctness of editor-vs-disk resolution, freshness and realistic integration signatures. Provide minimal amendments with observable distinguishing checks, or READY. Focus the agreed data slice. + +## 3. Scope and non-goals +Read-only, no active security investigation or exploit development. Review ordinary input names, disk changes, unsaved headers, alias behavior and invalidation. No filesystem isolation/driver launch implementation, no scope expansion. + +## 4. Files to inspect +Read T-SOURCE-CATALOG-009.md, T-SOURCE-OVERLAYS-009.md and T-SEMANTIC-LEASE-009.md, include/Void/LanguageServer/{Support/RegularFile,Documents/{DocumentStore,Uri},Build/Model}.hpp, src/Documents/{DocumentStore,Uri}.cpp and src/Build/ProviderFile.cpp. Review the named existing interface rather than restating idealized filesystem behavior. + +## 5. Write ownership and coordination +Write scope: none +Private build/preflight-catalog-009 direct source/benign temporary fixtures only if needed. No persistent changes, shared builds or delegated tasks. + +## 6. Implementation or investigation approach +Trace how a caller chooses an authorized root, how fd-based reading and a client URI bind a single physical source, handling of missing/uncreated/blocked/aliased overlays. Check current compare snapshots, retained fd/route lifetime, quota and parent changes. Distinguish explicit evidence for an observed exact lookup from evidence of complete compiler lookup coverage. Reuse recent preflight and original normal case tests; avoid rerunning unrelated review assignments. + +## 7. Interfaces and data contracts +Review proposed source root/session/authority scope and the exact document API capture_file_inventory/observe_bound_source/materialize_bound_disk/validate_bound_sources (see frozen task for spelling). Verify what is revalidated by the caller vs the captured data object, especially hardlinks and directory names. Return any objective missing contract preventing implementation. + +## 8. Dependencies and integration +Document and workspace lease packages are in progress with disjoint owners. The catalog owner can prepare file handling and digests before their headers finish. The downstream runtime controls private mounts, tool identity and complete input coverage independently. + +## 9. Edge cases security and performance +Resource limits, stable identity over replacement, nonblocking regular-file reading, atomic document authority, scope of partial/failed results and source mapping are relevant. Restrict to supplied repo and approved benign file fixtures. No independent exploratory tests on other targets. + +## 10. Acceptance criteria +Provide READY or CHANGES_REQUIRED in terms of a simple real source/lookup example, a source line and a test. The implementation tests must distinguish a new unsaved header, an empty file, a blocked open and an observed negative lookup that changes. Avoid unnecessary policy/UX requirements. + +## 11. Verification commands and evidence +Read-only file review; optional build/bootstrap/tests/vls_document_tests --no-color or targeted existing test. Record only actual checks. No shared manifests or configuration changes. + +## 12. Constraints and stop conditions +Stop and contact root for an actual gap requiring a new owner. Preserve continued independent diagnostic/graph work. + +## 13. Authorization and decisions +Full authorized roadmap D-022/025/027, independent reviewer specifically GPT-6.2 Astra Max D-029. No external publish/remote updates. + +## 14. Return format +T-PREFLIGHT-CATALOG-009 READY or CHANGES_REQUIRED with exact issues/lines/tests and ownership. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-DAP-020.md b/docs/agent-workflow/tasks/T-PREFLIGHT-DAP-020.md new file mode 100644 index 0000000..eec1a6e --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-DAP-020.md @@ -0,0 +1,49 @@ +# Preflight the recorded DAP session and inspection contract + +Task ID: T-PREFLIGHT-DAP-020 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +The real shared root is /home/faumaray/Projects/VoidLanguageServer. Work is on feat/implement-roadmap at ca04975 plus local changes. T-PLAN-DAP-020 designed the DAP path. T-REPLAY-RECORDING-019 implemented ReplayRecording. The existing four real 17/34 and 41/82 journals still replay from the CLI. Requirements R-017 through R-020 require DAP and custom inspection over one compiler session. Root owns DAP code and build integration, and the semantic reviewer owns an independent read-only review. + +## 2. Objective and deliverables +Check the following NEW DAP replay contract against actual source, compiler data and official DAP requirements. Identify concrete errors before implementation. Send a readiness verdict and distinguishing test. Verify the contract independently of root reasoning. + +## 3. Scope and non-goals +Focus on recorded sessions in a private stdio process, honest replay controls, frame/value/source mapping, bounded inspection, authority and test coverage. Actual live compiler control is a separate implementation on this same service. Avoid source edits, broad LSP reviews, compiler changes or external messages. + +## 4. Files to inspect +Read experiments/frontend/gcc-worker/{Trace.hpp,Trace.cpp,Main.cpp}, tests/debug/RecordingTests.cpp, docs/agent-workflow/tasks/T-{PLAN-DAP-020,PREFLIGHT-REPLAY-020}.md, docs/roadmap/{20-dap-service,21-inspection-api}.md, include/Void/LanguageServer/Protocol/{Framing,Json}.hpp. Use the official Microsoft DAP overview and specification for capability implications, configuration ordering, unavailable stack positions and paging. + +## 5. Write ownership and coordination +Write scope: none +Private benign fixtures only in build/preflight-dap-020. No writes to code, manifests or workflow docs, no Git changes, no subagents. Root coordinates application paths and integration. Avoid mutable VBS selection changes. + +## 6. Implementation or investigation approach +Review a standalone C++ vls-dap --replay ABSOLUTE_TRACE. Launch opens only the launcher-selected journal; optional matching trace argument verifies equality. Retain one immutable ReplayRecording across inspection. Reuse framing and strict JSON, keep DAP protocol sequence distinct from compiler signal and cursor. Respond to initialize before initialized. Accept configurationDone before or after launch; respond to configurationDone before the deferred launch response and then send stopped. Disconnect settles a deferred launch. Keep source-only, partial-prefix and empty recordings honest. + +## 7. Interfaces and data contracts +NEW DAP API supports initialize, launch, configurationDone, setBreakpoints (one unverified result per unsupported source breakpoint), empty setExceptionBreakpoints, threads, stackTrace, scopes, variables, loadedSources, source, continue, disconnect and terminate. Continue visits the next observed integral value with matching stop if present; source statement stepping remains unsupported. Logical declaration metadata stays in custom views, physical frame source is absent with line/column zero. The captured primary file has a positive session-lifetime sourceReference and no client-path reopening. Positive frame/scope references expire on every movement and never alias later stops in the same connection. Preserve signed integer precision/bits, provisional vs final outcomes and cached or missing values. NEW vls/session bootstrap returns schemaVersion=1, unique sessionId, generation, mode, eventSequence, pauseKind, sourceReference, compiler identity and separate recording-level outcome. NEW vls/timeline and vls/frames require schemaVersion, sessionId and generation, page start/count <=256, and return matching identity. NEW vls/seek is a DAP control with the same expected identity, and exactly one eventSequence or direction previousValue/nextValue. Successful movement responds before stopped, changes generation even after seeking back. A replay cursor can represent an event lacking a matching recorded compiler stop. Statement-granularity reverse/next is not advertised. + +## 8. Dependencies and integration +Captured source ownership includes binary input. Offer a positive sourceReference and a loadedSources entry only for representable UTF-8 bytes. Keep sourceAvailable, sourceByteLength and sourceSha256 in the custom session metadata for all recordings. Embedded NUL in valid text must survive JSON serialization, including at the 1 MiB raw limit. An unavailable source request cannot substitute a hex string or current disk content. +T-PLAN-DAP-020 and T-REPLAY-RECORDING-019 provide the existing index and public interface. No raw journal parser or duplicated timeline. Root will implement and test in both build systems, including staged VBS. A second owner may write process tests after the contract is frozen. + +## 9. Edge cases security and performance +No public network listener, arbitrary executable, debuggee argument forwarding or client-chosen source reads. Validate request types and integer variants. Cap malformed framing and selected journal using existing limits, preserve 1 MiB captured source through JSON expansion. Treat truncated/failed files, missing HELLO, terminal prefixes and expired handles honestly. At most 4096 events and 256 per custom page. Never expose current timeline state in a historical cursor. Limit handle allocation and output, keep bounded work without caching full stacks at every event. Handle back-to-back controls and EOF during configuration. + +## 10. Acceptance criteria +1. Check initialize/launch/configuration order and deferred-request cleanup against generic DAP clients. 2. Trace real events 5/6,7,8,9/10,11 and unpaired 20,22; preserve ack stop/action and provisional result. 3. Show that stale refs/pages, a replaced journal and a mismatching sourceReference cannot return another source or control a later generation. 4. Identify any reachable false capability, fake position, incorrect value or unbounded path. 5. Name the bounded correction and distinguishing acceptance check if necessary. + +## 11. Verification commands and evidence +From the shared root use build/bootstrap/tests/vls_trace_tests --list --no-color. Run build/bootstrap/vls_gcc_probe replay build/plan-dap-020/capture-16mqf07g/source17-stepped.vls 6 and 8. Compare source17-every-return.vls and source41-cancelled.vls at real event ordinals. For missing framing details inspect src/Protocol/Framing.cpp. Use source and official media; no external upload of repo contents. + +## 12. Constraints and stop conditions +Read-only scope. Report missing evidence or an incompatibility immediately. An unavailable upstream service only limits that research leg. No release or merging decision. No approvals or questions to the user. Return to the root. + +## 13. Authorization and decisions +Full roadmap implementation D-022, native priority D-025, authorized GPT-6.2 Astra at Max D-027/029. The user selected the generic runtime for the named review assignment. D-030 defers distribution of compiler changes. + +## 14. Return format +T-PREFLIGHT-DAP-020 READY or CHANGES_REQUIRED. Include findings, trigger, source/evidence, exact suggested amendment, commands and unrun checks. Send a ready independent slice early. Do not spawn children. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-DIAGNOSTIC-013.md b/docs/agent-workflow/tasks/T-PREFLIGHT-DIAGNOSTIC-013.md new file mode 100644 index 0000000..3157dea --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-DIAGNOSTIC-013.md @@ -0,0 +1,48 @@ +# Preflight stock GCC diagnostic locations and clean-result admission + +Task ID: T-PREFLIGHT-DIAGNOSTIC-013 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +VLS branch feat/implement-roadmap ca04975. Planner has a successful ordinary-GCC real-TU diagnostic probe. A pure SARIF adapter T-DIAGNOSTIC-SARIF-013 is proposed to support roadmap 09/13. Existing snapshots have UTF-8/16 conversion. Compiler outputs and working tree are available. + +## 2. Objective and deliverables +Review this particular assignment for meaningful implementation acceptance, especially what GCC SARIF does and does not prove about real source ranges, process success, partial source evidence and primary/related locations. Return an early implementable verdict. + +## 3. Scope and non-goals +Read-only preflight for this adapter only. No code changes, separate compiler gate, other worker ownership or external operations. + +## 4. Files to inspect +Read the attached implementation contract, source fixtures tests/corpus/frontend/{gcc-queries.cpp,verify-gcc-ide.py}, build/gcc-gate/{constraint,queries}.sarif, include/Void/LanguageServer/{Protocol/Json,Documents/{DocumentSnapshot,Position}}.hpp, docs/roadmap/13-diagnostics-recovery.md and relevant GCC16 SARIF source. Verify facts locally rather than infer from format name. + +## 5. Write ownership and coordination +Write scope: none +Optional private ordinary compiler fixtures under build/preflight-diagnostics-013. All shared code/docs/builds owned by root and separate workers. No child agents or user contact. + +## 6. Implementation or investigation approach +Examine actual GCC status/artifact representations, column convention and Unicode/BOM witness. Check proposed decoder's ability to produce a real positively bound result while withholding ambiguous origins and incomplete clean clears. Identify minimal additional gate or witness if needed. Distinguish structural failures from a valid source diagnostic with unlocated related data. + +## 7. Interfaces and data contracts +Public contracts proposed in T-DIAGNOSTIC-SARIF-013 section 7. Positive mapped outcomes have a retained exact document and verified physical origin; process outcome separate from bytes. Verify the design supports multiple artifacts/index/base references without reading arbitrary paths or pulling in an independent parser. + +## 8. Dependencies and integration +Milestone is independent of module graph, adapter does no process launching and will be used by the stock diagnostics worker. Root integrates native/CMake/actual gcc fixture. Implementation awaits reviewed interfaces; please issue early amendment only for consequential problems. + +## 9. Edge cases security and performance +Check bounded decoding and source materialization, integer range, endpoint ambiguity, partial compiler stderr, absence of expected result fields, diagnostics from headers/imports and stale snapshots. Use harmless ordinary compile fixtures. + +## 10. Acceptance criteria +READY or CHANGES_REQUIRED with exact contract section and distinguishing tests. Provide evidence for defaults and any important limits, including whether success/error SARIF can cause false clean clears or false source positions. + +## 11. Verification commands and evidence +git status --short --branch; actual local GCC16 reports and snapshot code. Optional focused stock syntax-only/diagnostic probe in your private directory. Report exact sources and checks; no edits/builds in shared areas. + +## 12. Constraints and stop conditions +No production backend/permission decisions, no expanded scope or changes. If rate-limited report honestly. Fast early verdict allows independent coding. + +## 13. Authorization and decisions +User wants full project with native VBS, GPT-6.2 Astra Max for independent review. D-028/030 approves local GCC prototype and evidence. Read-only task. + +## 14. Return format +T-PREFLIGHT-DIAGNOSTIC-013 READY/CHANGES_REQUIRED, necessary amendments and attested checks. Report to root. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-GCC-008.md b/docs/agent-workflow/tasks/T-PREFLIGHT-GCC-008.md new file mode 100644 index 0000000..2b297ab --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-GCC-008.md @@ -0,0 +1,49 @@ +# Review the private GCC worker and the first real evaluator and IDE hooks + +Task ID: T-PREFLIGHT-GCC-008 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975, dirty files authorized. Primary native descriptor build.cpp, optional CMake verification, VoidLibrary main 7d7d23e. T-PLAN-006 verified VBS 6c225c2 selector/status/generations and actual compdb rows. Build/Model.hpp, Workspace/{Configuration,Trust}.hpp and Protocol/Json.hpp are implemented. Root owns build/test registration, CLI, session, docs and integration. No shared tree branch switches, Git mutations, sibling writes, child agents or independent user messages. D-030 explicitly authorizes a local isolated GCC 16.2 worker + versioned compiler hooks. Root has built cc1plus from the verified release. Planner T-PLAN-GCC-008 mapped actual source and APIs. + +## 2. Objective and deliverables +Fresh independent preflight of the proposed compiler patch, worker launch/control boundary, direct IDE occurrences and debugger witness. Give per-slice verdicts and decisive changes; let independent implementation start when a slice is ready. + +## 3. Scope and non-goals +No code edits or publication. Probe only task-owned synthetic fixtures and exact local GCC source/evidence. No semantic fallback to raw-dump parsing in the product or exposure of experimental capabilities on ordinary LSP. + +## 4. Files to inspect +Read docs/roadmap/08*,09*,12*,17*,18*,19*, docs/agent-workflow/tasks/T-PLAN-GCC-008.md and actual implementation under build/gcc-gate/gcc-16.2.0/gcc/{cp/constexpr.cc,cp/parser.cc,cp/lex.cc,cp/Make-lang.in,cp/constraint.cc,cp/pt.cc,cp/reflect.cc,c-family/c.opt,json.h,diagnostics/sarif-sink.cc}. Verify exact source points below. Read tests/corpus/frontend/{gcc-live.cpp,gcc-queries.cpp,probe-gcc-tooling.py}, Build/Model.hpp, Workspace/Trust.hpp and build/voidlibrary/current/include/Void/System/Process.hpp. + +## 5. Write ownership and coordination +Write scope: none +Independent reviewer only. Root owns integration, checked source build and clients. Separate implementers will own compiler-patches/gcc-16.2.0/ and experiments/frontend/gcc-worker/ respectively; each gets an exact task after preflight. + +## 6. Implementation or investigation approach +Check core evaluator observation after admission/bindings at constexpr.cc 4279, real body 4531, copied result of get_value(res) at 4552 before destroy_value_checked at 4576; final error/outcome 4653, cache branch 4426 and exceptions. Ordinary successful integral return needs actual TYPE_PRECISION/signed/exact bits at event time. Use scope IDs/parents for recursion/early returns. Local compiler flags opt-in; disabled path has no formatting/I/O and preserves semantics. Review frontend-origin HELLO/EOF/finalization at cp/lex.cc 340/80 and fixed private pipe framing. Check saved/edit/malformed/recovered direct call (parser.cc 7150, 8941, 9129) at terminal identifier token, member use at 9639,9725. Require exact spelling bytes in immutable snapshot and same invocation DECL_UID; reject tentative/rolled-back evidence, macro/#line/generated/implicit or missing origins. Validate direct target rather than dumping all lexical spellings. + +## 7. Interfaces and data contracts +NEW private v1 interface proposal. Patch records on dedicated fd 4, bounded newline-delimited UTF-8 JSON frames of at most 64 KiB, parent control on fd 3, up to 4 KiB per control. Trusted launcher remaps Void::Process child pipes, isolates raw cc1 stdout/stdin, separately drains stderr and execs selected private ELF (absolute, stable open identity), with explicit environment/no PATH selection, process group and resource bounds. Request nonce/version + backend build/patch identity, contiguous seq and owned call IDs, kind/source origin and value DTO {kind:integer,precision,signed,bitsHex} or explicit unavailable. At actual value snapshot, can stop; only matched nonce/stop generation can step/continue/cancel. Buffer/cap/truncate with typed terminal reasons on overflow/crash, distinguish paused/running deadlines/EOF, reap whole group. One frozen fixed fixture per invocation, no arbitrary launch or flags from project metadata. Keep frontend diagnostics and IDE/debug records independently correlated and do not misread SARIF display columns as UTF units. + +## 8. Dependencies and integration +T-PLAN-GCC-008 source mapping complete. Known release SHA + tag, stock plugin and GDB evidence are partial; full compiler parity, hook values, source and state-machine tests remain mandatory. Root can continue provider implementation and standalone baseline build during your review. + +## 9. Edge cases security and performance +On resumption the evaluator slice has an independent READY verdict with amendments. T-GCC-EVALUATOR-017 records those amendments and the concrete v1 stream. The outstanding verdicts cover the worker launcher, control/replay and direct IDE evidence. The actual private cc1plus built and matched the stock predefined macros and all 19 reference cases, eight tooling cases and 33 module scans with the reference include roots and explicit PIE/preinclude flags. Verify remaining boundaries against source. Do not duplicate the accepted evaluator review except to report a concrete cross-component defect. +Guard GC tree lifetime, arbitrary widths, caching/silent failure/reentrant parsing, exceptions, real vs diagnostic replays; stable origin identity for src snapshot/macro/line directives, malicious strings cannot frame injection, pipe FD collision/EOF/kill/leaked descendants. Scope only claims actual direct expressions, ordinary ints/closed fixture. Later template/constraint/metafunction/splice/expansion hooks have separate source anchors; no silent classification of deferred as satisfied. + +## 10. Acceptance criteria +Compiler event vs supervisor vs IDE per-slice READY/CHANGES_REQUIRED. Require synthetic Ready=17→41 with same assertion >0 produces distinct real values 17/34, 41/82 with observed nested parent, held stop with same PID/no later events, step/cancel and mutation/replay witness. Require multi-occurrence direct overload definition/field/hover and malformed/recovered edits, raw byte accuracy incl Unicode/tab or explicit unavailable. Distinguish prototype success from full backend/debugger/adoption gates. + +## 11. Verification commands and evidence +Read bounded local GCC release slices and VLS graph coverage/direct source; use git status --short --branch and optional bounded known-fixture smoke with stock GCC, never modify in-progress compiler build. Return evidence and concrete distinguishing checks. No large new source/build downloads. + +## 12. Constraints and stop conditions +Report genuine blockers/change requirements early. Do not assume GCC public plugins alone provide evaluation state, invent compiler results, widen project license or invoke project metadata. Do not expand the narrow witness into a prerequisite for independent passive work. + +## 13. Authorization and decisions +User approved D-030 and retained independent Astra Max review in D-029. This new substantial change requires a fresh planner/preflight followed by source and integration review. No remote action/Git changes authorized. + +## 14. Return format +T-PREFLIGHT-GCC-008 per-slice verdicts, exact amendments/source anchors, test oracle, and separable work/actual blockers. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-LEASE-009.md b/docs/agent-workflow/tasks/T-PREFLIGHT-LEASE-009.md new file mode 100644 index 0000000..14c4941 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-LEASE-009.md @@ -0,0 +1,48 @@ +# Review stability and lifetime of the editor context lease + +Task ID: T-PREFLIGHT-LEASE-009 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Shared VLS feat/implement-roadmap ca04975; passive status, actual providers, authority pinning and guarded analysis model exist. Planner T-PLAN-SEMANTICS-010 established the new lease to connect actual compiler contexts to diagnostics; before implementation review the attached contract. + +## 2. Objective and deliverables +Return early READY or CHANGES_REQUIRED for a context lease that acquires a real selection, authenticates its selected driver and revalidates when inputs change without degrading unaffected documents. Catch new contract holes before worker coding. + +## 3. Scope and non-goals +Read-only preflight limited to the proposed semantic context acquisition API and relevant existing projection/selection and settings. Do not implement, do not change any tools or release/pin choices. + +## 4. Files to inspect +Read T-SEMANTIC-LEASE-009, actual src/WorkspaceSession.cpp, src/Build/{Model,CommandImport,CompdbProvider,VbsProvider,ProviderFile}.cpp, src/Workspace/Trust.cpp, include/vls/WorkspaceSession.hpp, include/Void/LanguageServer/Build/{Providers,Model}.hpp and semantic-planner notes in the contract. Existing docs/agent-workflow/DECISIONS.md supplies authority decisions. + +## 5. Write ownership and coordination +Write scope: none +Use private build/preflight-semantic-lease-009 for ordinary files if needed. Preserve shared checkout, no global or sibling changes, further agents, direct user contact, or process launches from workspace commands. + +## 6. Implementation or investigation approach +Trace how identical generation identity/selection, query aliases and distinct in-flight documents can remain correct. Scope frontend/driver distinction and trust generation checks. Look for precise minimal amendments affecting real users, selected command fidelity, lifetime, equality and false generation changes. + +## 7. Interfaces and data contracts +NEW acquire_semantic_context/validate from the attached §7, consuming existing TrustPolicy, SelectionState, generation/stamps and immutable document binding. Ensure no untrusted executable is selected implicitly, repeated ordinary provider status can't break cached selection and unrelated documents aren't serialized to one latest issuance. Check handling of staleness during validation. + +## 8. Dependencies and integration +Root owns integration; no active source writer for affected files until preflight clears them. Module graph and SARIF decoder are parallel separate owners. Passive provider already has working stdio/regression checks. + +## 9. Edge cases security and performance +Bound cache/history and return safe immutable lifetime after eviction or removal. Track observed change and affected context rather than arbitrary process lifetime for readiness. Check that explicit file/workspace, missing/native precedence and config source choose the real row. + +## 10. Acceptance criteria +Deliver concrete P1/P2 interface or ordering changes with a distinguishing fixture, then a READY verdict if scope is technically sufficient. No need to approve later compiler isolation or wire protocol here. + +## 11. Verification commands and evidence +git status --short --branch, targeted symbol/source inspection and existing build/bootstrap/tests/vls_workspace_tests --no-color if helpful. No commands on arbitrary project input or shared rebuilds. + +## 12. Constraints and stop conditions +Stop at preflight verdict; role must stay GPT-6.2 Astra at Max. No changes to product scope or user commitments. + +## 13. Authorization and decisions +D-022/025/027/029, approved full roadmap, first semantic context integration follows the planner. This assignment is independent review only. + +## 14. Return format +T-PREFLIGHT-LEASE-009 READY/CHANGES_REQUIRED with actual evidence, smallest amendment and test. Report to root only. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-MODULE-011.md b/docs/agent-workflow/tasks/T-PREFLIGHT-MODULE-011.md new file mode 100644 index 0000000..04fd811 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-MODULE-011.md @@ -0,0 +1,49 @@ +# Check module evidence, name resolution and partial graph admission + +Task ID: T-PREFLIGHT-MODULE-011 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Shared VoidLanguageServer feat/implement-roadmap ca04975. Root and the independent semantic planner just scoped T-MODULE-GRAPH-011 on the working tree. Stock GCC 16.2 produced 33 module/scanner checks. Existing BuildContext represents TU alternatives; native v1 does not attest library/dependency completeness. This is preflight, not postimplementation certification. + +## 2. Objective and deliverables +Resume preflight after the previous Astra reviewer identified membership/census and header-unit cache/input identity gaps, then hit HTTP 429 before final disposition. The amended implementation contract records those actual observations at §7, including GCC 0/0 versus the paper's 1/0. Re-read the amendments and return actionable remaining changes or READY. Deadline-sensitive implementation can proceed once the contract is cleared. +Inspect the actual module graph assignment and representative stock compiler rules, then return READY or necessary amendments for module scan admission, scope, scheduling and invalidation. Send the earliest usable contract as soon as possible. + +## 3. Scope and non-goals +Independent technical design review only. Do not design the full unrelated frontend, implement graph code, edit compiler, advertise capabilities or send user messages. + +## 4. Files to inspect +Read docs/agent-workflow/tasks/T-MODULE-GRAPH-011.md in full, docs/roadmap/11-cpp-modules.md, tests/corpus/modules/verify.py, include/Void/LanguageServer/{Build/Model,Protocol/Json}.hpp, actual bounded scan JSON in build/gcc-gate/private-modules.log and P1689R5 paper when needed. Actual language APIs and tests override a task author's assumptions. + +## 5. Write ownership and coordination +Write scope: none +Private benign fixtures only under ignored build/preflight-module-011. Do not change graph, captures, build-dir selections, shared source, git or siblings. No additional agents. + +## 6. Implementation or investigation approach +Check for unsupported-version/default semantics, failure status with rule output, distinction of -M -MG from warm -E -MD, header-unit lookup and partitions, negative membership, mixed commands/incomplete inventory, ambiguity resolution and graph budget failures. Distinguish verified ready order for known graph from all-project indexing or launch authority. + +## 7. Interfaces and data contracts +Proposed graph calls are pure decode_scan(expected target) and build_module_plan(identity-scoped inputs, requested key). Return owned rule, transitive dependency order, reverse consumers and structured blockers; never open paths. Confirm strong semantics for scan provenance, pointer lifetime, unit kind, expected output, explicit compatible domain and full inventory. Provide exact corrected interface if needed. + +## 8. Dependencies and integration +Implementation awaits your verdict, root will dispatch after resolving actionable items. Independent of ongoing review of GCC instrumentation. No production backend decision required. + +## 9. Edge cases security and performance +Verify bounded untrusted JSON/graph costs, deeply nested and high-degree graphs, unrelated component damage, determinism, immutable lifetime and reverse invalidation for added/missing provider or changed contents. Use only harmless finite data. + +## 10. Acceptance criteria +Send decisive verdict plus precise action for each material risk and distinguishing fixtures. Confirm whether a normal legal real GCC primary/partition/importer context, some with different per-TU flags, can actually be modeled. Check which header-unit semantics need an explicit unsupported/missing result. + +## 11. Verification commands and evidence +git status --short --branch; examine tests/corpus/modules/verify.py and the already verified saved module report. Optional run stock corpus via dev cpp-gcc -c python3 tests/corpus/modules/verify.py, no shared mutations. Bounded code graph queries with coverage as appropriate. Report which commands executed. + +## 12. Constraints and stop conditions +Stop after delivering preflight, or exact missing dependency; no implicit fallback model or authority. No shared Nix/config, source or compiler builds. + +## 13. Authorization and decisions +D-022/025/027/029 require full roadmap native VBS and independent GPT-6.2 Astra at Max. Review targets are engineering checks within established user scope only. + +## 14. Return format +T-PREFLIGHT-MODULE-011 READY / CHANGES_REQUIRED, evidence, concrete changes/test witnesses; send ASAP to root, no user messages. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-REPLAY-020.md b/docs/agent-workflow/tasks/T-PREFLIGHT-REPLAY-020.md new file mode 100644 index 0000000..086ee16 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-REPLAY-020.md @@ -0,0 +1,48 @@ +# Check immutable recording semantics for DAP and shared inspection + +Task ID: T-PREFLIGHT-REPLAY-020 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +T-PLAN-DAP-020 traced the current v1 validated journal, two actual compiler recordings and standard DAP scope. T-REPLAY-RECORDING-019 proposes an immutable one-time-validated recording; current replay(path,seq) rereads by pathname. This preflight fixes the records/view contract for an initial recorded DAP service. + +## 2. Objective and deliverables +Review the proposed immutable recording boundary against Trace.cpp and real fixture semantics. Verify enough true evidence is available for DAP inspection, separate recording state/end from event cursor state, and check source provenance and cost. + +## 3. Scope and non-goals +Read-only review of recording API and expected consumer, no DAP UI or control implementation. No reviewing OS isolation/third-party tools, and no new compiler hooks. + +## 4. Files to inspect +Inspect T-REPLAY-RECORDING-019.md, T-PLAN-DAP-020.md, experiments/frontend/gcc-worker/{Trace,Main}.cpp, Trace.hpp, tests/debug/TraceTests.cpp, docs/roadmap/20-dap-service.md. An actual 6,886-byte fixture resides in build/plan-dap-020/capture-16mqf07g/source17-every-return.vls, available via existing vls_gcc_probe replay if useful. + +## 5. Write ownership and coordination +Write scope: none +Optional small private build/preflight-replay-020 scratch only. No tracked writes, shared builds/branches, extra agents or remote sends. + +## 6. Implementation or investigation approach +Check the accepted trace event/manifest and record transitions (including commands vs resumed), prefix/corrupt detection, manifest/finish identity, scope of historical frame/variable data, missing physical coordinates, time/memory limits for index + query outputs. Map real 4-stop journal and replay failure evidence to requirements for DAP/custom requests. Test one or two discriminating current behaviors or use source + existing test evidence. + +## 7. Interfaces and data contracts +Evaluate open(absolute journal), event_count/page, typed real event summaries, cursor_at/event vs final cursor, raw source/diagnostics, capability and final outcome. Distinguish a caller-selected journal from an arbitrary client-provided source path. Preserve current CLI surfacing of partial/corrupt verified prefixes. If necessary amend exact stop/next definitions or consumption of source/shape before worker starts. + +## 8. Dependencies and integration +Existing Trace is released. Downstream DAP and custom session services consume this data and own handle/connection lifetime independently. Root verifies normal compiler tests and both builds. No other owner needs these files. + +## 9. Edge cases security and performance +Focus realistic time/space, old-recording immutability, clipped verified prefixes, retained sources and cursor-vs-outcome correctness. Keep bounded tests and existing ownership. Do not introduce new production policy requirements. + +## 10. Acceptance criteria +READY or CHANGES_REQUIRED with exact source lines, involved actual events, minimal amendment and distinguishing test. Explicitly separate prerequisites for this data slice from later DAP/live features. + +## 11. Verification commands and evidence +Read-only. Optional run build/bootstrap/tests/vls_trace_tests --no-color, build/native-validation/profiles/debug/out/bin/vls_gcc_probe replay ABS/real.vls 6. Only report actual observed statuses. + +## 12. Constraints and stop conditions +Stop for ambiguous ownership or an incompatible change in existing trace wire contract. Return early actionable findings to parent. + +## 13. Authorization and decisions +Approved local full roadmap, independent GPT-6.2 Astra Max D-027/029. No deployment or compiler distribution. + +## 14. Return format +T-PREFLIGHT-REPLAY-020 READY or CHANGES_REQUIRED with dynamic/static evidence and next independent owners. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-SOURCE-009.md b/docs/agent-workflow/tasks/T-PREFLIGHT-SOURCE-009.md new file mode 100644 index 0000000..e7e3f50 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-SOURCE-009.md @@ -0,0 +1,48 @@ +# Check the editor overlay handoff for a stock compiler input view + +Task ID: T-PREFLIGHT-SOURCE-009 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Roadmap 03/09/13 has a working overlay store, stock GCC diagnostic mapper and trusted build-context/lease contract. T-SOURCE-OVERLAYS-009 proposes a document-side source binding for a future real compiler view. + +## 2. Objective and deliverables +Read the actual DocumentStore and the proposed contract. Validate the minimum API for a stock input owner to materialize approved bytes plus authoritative editor overlays and recheck them, with no second ambient open. Identify required corrections before code starts. + +## 3. Scope and non-goals +Preflight read-only for the document capture contract; no review of other components or new architecture beyond this boundary. No compiler launches or security testing needed. No filesystem staging, LSP work or source-checker implementation. + +## 4. Files to inspect +Read docs/agent-workflow/tasks/T-SOURCE-OVERLAYS-009.md and T-DOCS-003.md, include/Void/LanguageServer/Documents/{DocumentStore,DocumentSnapshot,Uri}.hpp, src/Documents/{DocumentStore,DocumentSnapshot,Uri}.cpp, tests/documents/DocumentTests.cpp and relevant model eligibility in src/Build/Model.cpp. Inspect actual state transitions and retained budget; never inspect excluded environment data. + +## 5. Write ownership and coordination +Write scope: none +A private bounded build/preflight-source-009 fixture may be used to validate a neutral regression, but no shared mutations or extra agents. + +## 6. Implementation or investigation approach +Trace overlay acquisition, unknown and refused opens, zero-length content, two physical aliases, close/reopen, recovery/desync with unchanged version, same_input_as, snapshot bytes, membership and concurrent edits. Read all methods receiving already-bound paths; verify cross-store and cross-generation stamps do not require IO. Distinguish evidence the document owner can establish from the future disk/namespace catalog. + +## 7. Interfaces and data contracts +Review proposed opaque bounded inventory and one-file bound observation, post-read creation and validity. Require missing, refused, invalid and available state to remain distinct; no need to prescribe new public types if an existing type suffices. Existing disk resolve remains a separate entry point with ambient reads. + +## 8. Dependencies and integration +One cleared semantic planner and document foundations are prerequisites. Independent workspace/diagnostic/module tasks own no overlapping file. Report early verdict as soon as API can be implemented; root handles code and wiring after READY. + +## 9. Edge cases security and performance +Review for concrete failures observable in an editor or compiler input, overbroad invalidation, deadlocks, identity lifetimes and retained budget. Bound any diagnostics/distinguishing fixtures. No external network, project discovery or stress beyond ordinary unit inputs. + +## 10. Acceptance criteria +READY if scope and contract give a credible first stock diagnostic handoff. Otherwise give exact minimal amendments and a distinguishing test. Include concrete source lines, note actual reads versus unrun tests and outstanding caller responsibilities. + +## 11. Verification commands and evidence +Inspect checked-in baselines and latest changed files; optional build/bootstrap/tests/vls_document_tests --no-color or --list, no shared build changes. Record actual command and exit if running tests. + +## 12. Constraints and stop conditions +Stop for ambiguous project identity or ownership. Source materialization, verified catalog closure and OS isolation will get separate integration gates. Do not make unrelated work a precondition for the document package. + +## 13. Authorization and decisions +User authorized separate-branch full implementation D-022/025/027 and wants independent Astra at Max D-029. + +## 14. Return format +T-PREFLIGHT-SOURCE-009 READY or CHANGES_REQUIRED with lines, needed clauses and distinguishing cases, plus final ownership and next unblocked work. diff --git a/docs/agent-workflow/tasks/T-PREFLIGHT-STOCK-NAVIGATION-014.md b/docs/agent-workflow/tasks/T-PREFLIGHT-STOCK-NAVIGATION-014.md new file mode 100644 index 0000000..04a390a --- /dev/null +++ b/docs/agent-workflow/tasks/T-PREFLIGHT-STOCK-NAVIGATION-014.md @@ -0,0 +1,48 @@ +# Preflight stock GCC observation and its editor authority +Task ID: T-PREFLIGHT-STOCK-NAVIGATION-014 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Shared VoidLanguageServer ca04975 on feat/implement-roadmap. T-PLAN-STOCK-NAVIGATION-014 obtained a real stock-GCC match for the saved and edited Void::Hash::fnv1a64 call and tested two same-line overloads. A hidden same-name macro can leave all ordinary CALL_EXPR endpoint locations, and a dependent wrapper may resolve twice at the identical token. The stock worker already closes lookup inputs for LSP diagnostics. Frozen candidate producer contract accompanies this spec. + +## 2. Objective and deliverables +Independently preflight T-STOCK-OCCURRENCES-014 and the eventual reader/worker/editor boundary. Return early separate producer and consumer verdicts so bounded implementation may begin. Identify distinguishing tests for false semantic facts and authorization/regressions. No implementation. + +## 3. Scope and non-goals +Stock GCC 16.2 optional approved observer for direct-call return type/definition. User project compiler stays unchanged. No live DAP, project rename, generated reflection semantics or other backend selection. + +## 4. Files to inspect +Review docs/agent-workflow/tasks/T-{STOCK-OCCURRENCES-014,PLAN-STOCK-NAVIGATION-014}.md including full producer contract. Inspect private source build/plan-stock-navigation-014/observe.cc, relevant evidence, include/vls/semantic/{StockCompiler,SourceCatalog}.hpp, src/semantic/{StockCompiler,EditorDiagnostics}.cpp, src/Server.cpp, src/Build/Model.cpp, tests/corpus/frontend/gcc-queries.cpp and actual stock plugin headers. Review published operator precedence and source-location semantics if necessary using official GCC source. No project data in public requests. + +## 5. Write ownership and coordination +Write scope: none +Private checks under build/preflight-stock-navigation-014 only. No application or task edits, shared compiler/builder execution, changing editor selections or shared profiles. No subagents. Return to root only. + +## 6. Implementation or investigation approach +Check native plugin API can prove the identity of the selected call and an actual function body. Challenge token-to-byte mapping for hidden macro maps, duplicated/qualified names, line remaps, BOM/tabs, declared-only targets, template instantiations sharing physical occurrences and cross-file header edits. Check per-job stdout/stderr separation, dynamic loader inputs, bounded report, closed mounts, and LSP location/hover correctly tied to receiver and version. Require clear and stale outcomes to distinguish unsupported, interrupted and complete. + +## 7. Interfaces and data contracts +Initial wire is in T-STOCK-OCCURRENCES-014 §7. Root proposes an explicit trusted GCC profile option for a fixed ABI observer digest. Capture the verified plugin bytes from the same opened object and bind a private copy read-only at /vls-observer/occurrences.so for the isolated run; only the exact instrumentation inputs and report file receive infrastructure access. Original source spellings are matched to the final source capture. Compdb, initialization options and workspace settings cannot select a plugin or alter its args. On a verified successful run, retain per-TU facts under the selected capture. Revalidate receipt, issuer, source closure and chosen edition before answering hover/definition; emit capability only on opt-in launch. Use a specific occurrence proof and readiness separate from project-wide completeness and diagnostic cleanliness. Client asks ordinary LSP requests at negotiated position. Unknown calls and prior revisions must not authorize links. If a shadow or negative lookup changes, invalidate cache. Distinguish overlay coordinates from disk targets unchecked by clients. + +## 8. Dependencies and integration +The producer's tool and host contract now include the linker's effective ELF search paths and dependencies. The observed planner binary has a project RUNPATH. The worker must refuse this object and admit a prepared object with verified immutable resolution. +Existing opt-in stock GCC profiles, immutable source catalog and real diagnostics server. Root owns producer/decoder schema, integration build + tests, and any version-selective capabilities. Existing code imposes conservative directory, symlink, manifest and process limits, so do not add a generic escape hatch. Fresh corpus is allowed only on task-owned minimal source/stock compiler. + +## 9. Edge cases security and performance +Bound macro maps (real Void TU observed 26,106), path input counts, generated source, retained queries and lifecycle. Test false positives caused by GCC coordinate normalization or a target declared in an included header but defined elsewhere. Check a plugin change after profile selection and source changes between compilation and LSP response; local trusted binaries only, no remote service. No project license decision in this assignment. + +## 10. Acceptance criteria +1. Early positive/changes-required verdict for the producer. 2. Separate disposition with precise host proof/receipts for opt-in publication. 3. Identify any service-facing risk or proven unsoundness and its minimal distinguishing test. 4. Keep genuine high-impact uncertainty visible and allow independent work to proceed once amended. + +## 11. Verification commands and evidence +Run dev cpp-gcc -c g++ --version, inspect build/plan-stock-navigation-014/real-{saved,edited,broken,recovered}.json and actual code. If needed, build a benign isolated counterexample with stock GCC under own build path. No project build or compiler edits. Distinguish a source-backed assertion from a runtime proof. + +## 12. Constraints and stop conditions +Read-only review; no source edits; stop on a genuine unavailable fact and return the specific missing evidence. Do not review unrelated product areas or seek user approval independently. No Git operations or external messages. + +## 13. Authorization and decisions +D-022 full roadmap, D-025 native primary, D-027/029 user selects GPT-6.2 Astra at Max for review, D-028/030 local experiments. Existing GCC and normal compilation remain available. + +## 14. Return format +T-PREFLIGHT-STOCK-NAVIGATION-014 READY/CHANGES_REQUIRED with separate producer and host gates, actual paths/tests, proposed amendments and unrun checks. Send early verified findings; no subagents. diff --git a/docs/agent-workflow/tasks/T-PROTOCOL-005.md b/docs/agent-workflow/tasks/T-PROTOCOL-005.md new file mode 100644 index 0000000..44dee08 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PROTOCOL-005.md @@ -0,0 +1,57 @@ +# Unify framing and JSON adapters and use checked response serialization + +Task ID: T-PROTOCOL-005 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Repository /home/faumaray/Projects/VoidLanguageServer on feat/implement-roadmap, base ca04975. The bootstrap vls namespace has known working framing/lifecycle behavior. The new untracked Void::LanguageServer::Protocol duplicated that adapter before checked StrictJson serialization landed on main 7d7d23e. Source ownership was released by the original writer. T-PLAN-002 and the preflight direct one canonical implementation. + +## 2. Objective and deliverables +Expose one implementation of checked framing/JSON helpers and preserve compatibility for existing vls consumers. Make all response encoding failures explicit and use upstream serializer. Provide tests of escaping, round-trip, depth/UTF-8 and failure behavior. Root owns stdio dispatch and integration. + +## 3. Scope and non-goals +Protocol adapter and narrow compatibility headers only. Numeric exactness needs raw token metadata that current upstream lacks. Preserve existing request_id behavior on currently representable inputs, carry an explicitly open upstream gate and keep the new raw-wire regressions enabled. Do not develop a second JSON/decimal parser. + +## 4. Files to inspect +Read include/{vls,Void/LanguageServer/Protocol}/{Json,Framing}.hpp and their source implementations, src/Server.cpp and tests/{FramingTests,JsonTests,LifecycleTests,JsonCapabilities}.cpp, docs/roadmap/02-lsp-protocol-lifecycle.md. Compare the actual upstream parse and checked serialize in build/bootstrap/_deps/voidlibrary-src/include/Void/Data/StrictJson.hpp. Inspect CMakeLists.txt and T-NATIVE-001 for target ownership. + +## 5. Write ownership and coordination +Write scope: include/Void/LanguageServer/Protocol; src/Protocol; include/vls/Framing.hpp; include/vls/Json.hpp; src/Framing.cpp; src/Json.cpp; tests/ProtocolEncodingTests.cpp +No edits to build.cpp or CMake, existing suites, Server.hpp/cpp or sibling checkouts. Other agents share the branch and handle these paths. Keep old implementation paths usable until root wires both builds, and arrange final removal of dead forwarding translation units with root. + +## 6. Implementation or investigation approach +Compare the two adapters and choose the canonical behavior covered by the bootstrap. Replace the custom serializer with StrictJson::serialize and convert its error type into an explicit error result. Retain ingress validation/depth bounds. Keep IDs signed-32-bit integer or string and preserve checks on numeric decoded values. For unrepresentable exact tokens, coordinate against the upstream gate instead of guessing. Compatibility headers import canonical types/functions without copying algorithms. Give root the interfaces needed to create typed JSON responses. Preserve exact frame size/input handling; mark any new egress limit or failure contract for caller. + +## 7. Interfaces and data contracts +Canonical Json and RequestId keep their current types on upstream main. serialize_json(const Json&, std::size_t maximum_depth = 64) returns std::expected. Keep Protocol helpers find_member/as_object/as_array/as_string/as_bool/as_int64/as_uint32 for other slices, with checked type/range semantics. FrameLimits defaults to 8192 and 16777216. Expose public API for checked envelope egress. One implementation is linked per executable. If preserving legacy quote_json/encode_id as wrappers until root rewires server, document the migration and do not silently fabricate data. + +## 8. Dependencies and integration +Root serializes build definitions and actual error/result dispatch. Native migration is in progress. To keep it buildable, use a staged migration with root; avoid deleting definitions while their only target still references the old files. Hand off canonical source list and precise switch steps. The formal JSON exactness fix requires upstream release/override verification. Docs/workspace tests are disjoint. + +## 9. Edge cases security and performance +Invalid UTF-8 object keys/values, nonfinite manually constructed doubles and over-depth values must return an error and produce no partial protocol frame. Before/after framing boundaries must match including CRLF and clean EOF. Keep JSON handling bounded and avoid reparsing serialized request IDs. Preserve tested stdio behavior and document any remaining legacy transitional limitations. + +## 10. Acceptance criteria +1. Canonical namespace and vls source-compatibility resolve to one set of framing/JSON definitions after root integration. +2. Checked serialization propagates upstream failures and round-trips complex valid values including decimal numbers, controls and escaped data. +3. All original framing/lifecycle/ID cases retain behavior. The known precision/range failures remain visible until upstream resolves them. Actual failures and registration evidence are returned. +4. Expose unambiguous checked egress and typed ID helpers for root's Server integration. + +## 11. Verification commands and evidence +Root has used dev cpp-gcc -c cmake --build build/bootstrap --parallel 2 and dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure. For an isolated focused binary, use dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/bootstrap/_deps/voidlibrary-src/include with your canonical sources/tests, using observed Void::Testing archives in build/vbs-framework-probe or the existing bootstrap tree. Put artifacts under build/protocol-check. Test with --list --no-color and actual filtered bodies. Format owned files only. + +## 12. Constraints and stop conditions +Stop before writing other workers' build or session files and before changing numeric semantics without evidence. If a proposed signature breaks a consumer contact root with locations and the narrowest remedy. Stop after two unsuccessful repairs of the same defect and return evidence. No per-dependency source patches in this task. + +## 13. Authorization and decisions +D-021, D-022, D-024, D-025, D-026 and D-027. Protocol cleanup is within requested implementation and user approved continuation from the existing files. Use GPT-6.2 Sol at Max for this package after fresh preflight. No external writes, staging, commits or global settings. + +## 14. Return format +Return T-PROTOCOL-005 DONE/PARTIAL/BLOCKED, source paths, signatures/integration steps, commands and exit codes, case counts, original vs new coverage, any observed limitation and required wiring. No children or user messages. + +Fresh preflight found that StrictJson::serialize(maximumDepth=64) can admit the +65th empty container, whereas VLS ingress counts every container opening. Make +egress and ingress agree at 64, including empty containers and root scalars at +depth 0. Keep this bounded even for arbitrarily deep in-memory values. Switch +legacy/new headers, sources and build wiring in one coordinated root integration. diff --git a/docs/agent-workflow/tasks/T-PROVIDER-IO-007.md b/docs/agent-workflow/tasks/T-PROVIDER-IO-007.md new file mode 100644 index 0000000..b43741d --- /dev/null +++ b/docs/agent-workflow/tasks/T-PROVIDER-IO-007.md @@ -0,0 +1,49 @@ +# Bounded workspace-scoped metadata reads + +Task ID: T-PROVIDER-IO-007 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975, dirty files authorized. Primary native descriptor build.cpp, optional CMake verification, VoidLibrary main 7d7d23e. T-PLAN-006 verified VBS 6c225c2 selector/status/generations and actual compdb rows. Build/Model.hpp, Workspace/{Configuration,Trust}.hpp and Protocol/Json.hpp are implemented. Root owns build/test registration, CLI, session, docs and integration. No shared tree branch switches, Git mutations, sibling writes, child agents or independent user messages. + +## 2. Objective and deliverables +Implement passive input acquisition and revalidation for both build providers with scoped authority before any payload bytes are read. + +## 3. Scope and non-goals +Linux-first metadata acquisition. Preserve the behavior of existing unscoped selected-user-file, document and executable callers. No JSON, command parsing, compiler execution, discovery or file writes in providers. + +## 4. Files to inspect +Read include/Void/LanguageServer/Support/RegularFile.hpp and its current callers in Documents/DocumentStore.cpp and Workspace/{Configuration,Trust}.cpp, Providers.hpp proposal below and T-PLAN-006. Use existing Void::System::OwnedFd and Void::Crypto SHA-256. + +## 5. Write ownership and coordination +Write scope: include/Void/LanguageServer/Support/RegularFile.hpp; src/Build/ProviderFile.cpp; tests/build/ProviderFileTests.cpp +Existing shared helper is exclusively yours after the torn-read review correction, follow its established overload or factor the already-open descriptor logic. Others only consume public header. + +## 6. Implementation or investigation approach +Use pinned dirfd rooted admission and a stable regular-file FD (Linux openat2 beneath a verified scope or equally provable traversal); avoid prechecks followed by an independent pathname open. Reject an unprovable route. Admission checks logical pathname, target and purpose before streaming. Distinguish missing, outside scope, not regular, exceeded limit and change. Recheck root, logical and opened referent after streaming and on current(). Hash byte content while reading with VoidLibrary, preserve the logical locator base even when following a permitted symlink. Avoid opening FIFO/device content. Reject invalid path/NUL/over-limit. + +## 7. Interfaces and data contracts +NEW namespace Void::LanguageServer::Build. Root owns Providers.hpp. ProviderScope contains WorkspaceIdentity workspace, optional absolute exact_database, exact_selector, build_root, producer_cwd (root-bound launcher grants only) and Workspace::ResourceLimitsConfig limits. enum FilePurpose {selection,status,database,response}; read_provider_file(scope,path,purpose,byte_limit) returns expected; provider_file_current(scope,file) revalidates identity. ProviderFile has purpose, logical_path, canonical_path, bytes, content_id, stamp; stamp binds admission root, opened object and selected name. ProviderIssue has string code,message and filesystem::path path. DatabaseInput has const ProviderScope& scope, const ProviderFile& database, optional profile, optional driver; DriverInput holds a workspace/purpose/generation checked Workspace::ToolCheck and Workspace::CompilerDriver, plus known wrapper spellings. import_commands(const DatabaseInput&) returns expected; ImportedCommands has vector contexts, vector dependencies and string revision. ProviderObservation has string provider, optional selection_ticket, optional profile, Generation generation, vector issues and vector inputs; fresh is a generation without blocking issues (row limitations stay in context). observe_vbs(scope, selector_path, optional), observe_compdb(scope, database_path, optional) return ProviderObservation. Root owns latest sequenced publication and revalidation at install. All reads are passive. Concrete spelling in forthcoming header coordinated by root after preflight. + +## 8. Dependencies and integration +Root freezes header and wires targets. Each workspace has separate user/CLI-selected exact file(s), optional explicit build tree and known producer base. An exact external database admits only that named file; relative response inputs remain workspace scoped. Explicit build tree can admit VBS profile metadata and selected immutable DB only, never responses. Classify native generation DB separately if the normal database purpose would elevate an unrelated input; tell root any API amendment. + +## 9. Edge cases security and performance +T-PREFLIGHT-007 amendments now on the actual Providers.hpp: implement bind_provider_scope(ProviderScope) -> expected that pins workspace/build root and exact external parents once per settings grant/incarnation. Readers reject unbound scopes and any change in root/grant fields, symlinked/unprovable roots or redirected names, including replacement between binding and the FIRST read. A legitimate atomic leaf replacement is eligible on a fresh capture; stale retained files fail current(). Implement same_provider_object(a,b) noexcept using stable opened dev/inode for hard-link @ cycles. Preserve every logical name on retained files. Reserve issue code "missing" for proven absence of a path component through an admitted anchored directory, never a dangling link, nonregular file, unsafe traversal or denied access. Only genuine selector absence permits automatic compatibility fallback. Test hard links, an external parent replaced after binding, legitimate leaf replacement, dangling/symlinked presence and bounded observers. The opaque ProviderAnchors and ProviderStamp are yours to implement in ProviderFile.cpp. Treat FilePurpose::native_database as distinct. A build root grant restricts both shape and profile/generation path as specified. +Read quota bounds regular file streaming. For external exact file use a captured approved identity or freeze its intended authority under hostile alias replacement; untrusted writable link changes must not redirect an exact authorized file to arbitrary external targets. Same-object stable state + namespace binding and change detection for concurrent reads. Do not return retained bytes via equality/revalidation alone. No process invocation. + +## 10. Acceptance criteria +Nonzero ProviderFiles suite covers workspace success, permitted interior link or stated unsupported links, escape/changed-link refusal, exact-file isolation, restricted build purpose, response outside workspace, nonregular/bounded files, changed contents, root/name replacement and validity after unrelated changes. Real executable test/fixture may be used only as inert data. + +## 11. Verification commands and evidence +Use git status --short --branch, scoped graph coverage plus direct reads, dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only on the owned sources and tests, then link/run the actual Void::Testing suite in a private build subdirectory. Use dev cpp -c clang-format --dry-run --Werror on owned C++ paths. List the cases via --list --no-color. Root owns the two shared build trees. + +## 12. Constraints and stop conditions +Stop for incompatible existing helper callers, unresolvable authorization before reading or repeated repair failure. Explain any limitations and leave denied reads passive. + +## 13. Authorization and decisions +D-022, D-025–027. This is a bounded implementation of the independently planned read boundary; changes outside this repository require separate authorization. + +## 14. Return format +T-PROVIDER-IO-007 DONE/PARTIAL/BLOCKED, paths, scope matrix, stamp design, actual tests and residual issues. Send early frozen implementation detail needed by providers. diff --git a/docs/agent-workflow/tasks/T-PROVIDER-ROWS-007.md b/docs/agent-workflow/tasks/T-PROVIDER-ROWS-007.md new file mode 100644 index 0000000..94233e7 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PROVIDER-ROWS-007.md @@ -0,0 +1,49 @@ +# Import compile commands and preserve their provenance + +Task ID: T-PROVIDER-ROWS-007 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975, dirty files authorized. Primary native descriptor build.cpp, optional CMake verification, VoidLibrary main 7d7d23e. T-PLAN-006 verified VBS 6c225c2 selector/status/generations and actual compdb rows. Build/Model.hpp, Workspace/{Configuration,Trust}.hpp and Protocol/Json.hpp are implemented. Root owns build/test registration, CLI, session, docs and integration. No shared tree branch switches, Git mutations, sibling writes, child agents or independent user messages. + +## 2. Objective and deliverables +Implement the shared compilation database row reader used by both VBS and compdb. Emit deterministic one-TU contexts and bounded, compiler-specific response-file handling. + +## 3. Scope and non-goals +Passive data normalization and classification only. No shell, compiler, actual query, managed aliases or provider publication. No synthetic identities or authoritative missing fields. + +## 4. Files to inspect +Read Build/Model.hpp, Workspace/{Configuration,Trust}.hpp, src/Workspace/Trust.cpp, Protocol/Json.hpp, roadmap 07, T-PLAN-006. Read only actual VLS-generated build/bootstrap/compile_commands.json and a generated VBS compdb inside build/native-validation for representative rows. Exact schema primary source https://clang.llvm.org/docs/JSONCompilationDatabase.html. + +## 5. Write ownership and coordination +Write scope: src/Build/CommandImport.cpp; tests/build/CommandImportTests.cpp +No shared header edits. Root owns Providers.hpp. Coordinate needed support contracts before use. + +## 6. Implementation or investigation approach +Bound bytes, rows, tokens, depth, argv expansion and aggregate retained inputs before huge DOM allocations. Consider per-row structural slicing with quoted-string/escape handling and strict Void JSON per complete row; preserve the exact raw row. Reject malformed database structures atomically; keep recognizable but unsupported rows as explicit passive status with unknown semantic argv. Prefer typed arguments over command; malformed supplied arguments must not silently fall back. Linux quoted command tokenizer supports compdb documented double/backslash form and bounded explicit POSIX subset; never evaluate shell substitutions or expand globs/env. Against supplied real, same-root/compiler-purpose driver evidence apply its response grammar and recursive @ expansion relative to invocation cwd, detect cycles by file identity, bound aggregate bytes/tokens/depth, retain response inputs. For no driver leave response/unsafe argv as explicit unknown. Strip verified compile-only -o argument/output from semantic copy, retain original, normalize only understood flags and operands; do not alter forced-include/search semantics. Call existing Trust classifier before exposing runnable-view semantics, preserve all flags including unsupported reasons. No executable lookups based on submitted records. + +## 7. Interfaces and data contracts +NEW namespace Void::LanguageServer::Build. Root owns Providers.hpp. ProviderScope contains WorkspaceIdentity workspace, optional absolute exact_database, exact_selector, build_root, producer_cwd (root-bound launcher grants only) and Workspace::ResourceLimitsConfig limits. enum FilePurpose {selection,status,database,response}; read_provider_file(scope,path,purpose,byte_limit) returns expected; provider_file_current(scope,file) revalidates identity. ProviderFile has purpose, logical_path, canonical_path, bytes, content_id, stamp; stamp binds admission root, opened object and selected name. ProviderIssue has string code,message and filesystem::path path. DatabaseInput has const ProviderScope& scope, const ProviderFile& database, optional profile, optional driver; DriverInput holds a workspace/purpose/generation checked Workspace::ToolCheck and Workspace::CompilerDriver, plus known wrapper spellings. import_commands(const DatabaseInput&) returns expected; ImportedCommands has vector contexts, vector dependencies and string revision. ProviderObservation has string provider, optional selection_ticket, optional profile, Generation generation, vector issues and vector inputs; fresh is a generation without blocking issues (row limitations stay in context). observe_vbs(scope, selector_path, optional), observe_compdb(scope, database_path, optional) return ProviderObservation. Root owns latest sequenced publication and revalidation at install. All reads are passive. Concrete spelling in forthcoming header coordinated by root after preflight. + +## 8. Dependencies and integration +ProviderFile implementation arrives concurrently. Reuse only its validated read + revalidation; no separate path IO for metadata or @files. Root wires tests. Use original directory of logical selected database to resolve a relative row directory; subsequent relative row paths use invocation cwd. Test command-only, arguments, and actual VBS repeated flags with -o. + +## 9. Edge cases security and performance +T-PREFLIGHT-007 amendments. Use the actual Providers.hpp, same_provider_object for recursion-stack identity, and exact logical spelling for each retained observation. Before reading any response file, verify that the raw wrapper/compiler prefix matches the supplied real compiler pin for this root/purpose/driver. A mismatched compiler yields zero response-file reads. After classification require the only normalized TU to equal row.file; strip -o only at a verified option boundary, resolving/checking optional row.output against the same cwd. Reject symlink-sensitive ".."/search operands from semantic promotion. A row for A that compiles B keeps its original evidence and a limitation. Test that case, an unmatched compiler with a benign @response body, repeated legitimate nonrecursive @File, a hard-linked cycle, -o consumed as another option's operand, and repeated flags. Never turn allowlisted rows into independent execution approval. +Context alternative identity must survive row reordering, preserve multiplicity of identical rows with ordinal and conflicting options. Bound strings, extension nesting, escaped quotes, response byte amplification, option argument counts, generation memory. Preserve unknown v1 source mappings and edit origins when evidence is missing. Any hash collision requires detection or structurally unambiguous identity. Include raw bytes in original_record, including unsupported extension fields. + +## 10. Acceptance criteria +CommandImport suite exercises valid/invalid args/command, relative db/cwd and Unicode, multiple duplicate/conflicting entries, benign shell markers (remain inert), unsupported drivers/options, -o/forced includes, GCC/Clang response quoting and cwd, self and indirect cycles, size/depth/token limits, changed response, wrong-root/purpose driver and stable alternatives across ordering. Successful real CMake and VBS rows can be read without authority with explicit limitations. + +## 11. Verification commands and evidence +Use git status --short --branch, scoped graph coverage plus direct reads, dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only on the owned sources and tests, then link/run the actual Void::Testing suite in a private build subdirectory. Use dev cpp -c clang-format --dry-run --Werror on owned C++ paths. List the cases via --list --no-color. Root owns the two shared build trees. + +## 12. Constraints and stop conditions +Contact root before introducing a new parser for JSON values, guessing a driver from a basename, changing the Trust classifier or accepting a fallback with hidden semantics. After two failures change hypothesis with root. + +## 13. Authorization and decisions +D-022/D-027 and planner review. Compiler-specific normalization is optional only where real driver identity is absent. Never grant execution from this module. + +## 14. Return format +T-PROVIDER-ROWS-007 DONE/PARTIAL/BLOCKED, actual accepted/rejected grammars/tests/limits, real row evidence and unresolved integrations. diff --git a/docs/agent-workflow/tasks/T-PROVIDER-SESSION-007.md b/docs/agent-workflow/tasks/T-PROVIDER-SESSION-007.md new file mode 100644 index 0000000..9964a47 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PROVIDER-SESSION-007.md @@ -0,0 +1,49 @@ +# Select and expose passive providers through the running server + +Task ID: T-PROVIDER-SESSION-007 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975, dirty files authorized. Primary native descriptor build.cpp, optional CMake verification, VoidLibrary main 7d7d23e. T-PLAN-006 verified VBS 6c225c2 selector/status/generations and actual compdb rows. Build/Model.hpp, Workspace/{Configuration,Trust}.hpp and Protocol/Json.hpp are implemented. Root owns build/test registration, CLI, session, docs and integration. No shared tree branch switches, Git mutations, sibling writes, child agents or independent user messages. + +## 2. Objective and deliverables +Connect root-bound configuration and sequenced native/compdb observations to the real stdio server. Provide an inspectable first user-facing build integration. + +## 3. Scope and non-goals +Only passive metadata and status. No invented completion/navigation or compiler launches. Keep existing lifecycle and editor sync behavior; future analysis work consumes guarded generations. + +## 4. Files to inspect +Inspect src/{main,Server,DocumentSync}.cpp, include/vls/Server.hpp, actual Protocol/Workspace/Build models, T-PLAN-006 and provider tasks. + +## 5. Write ownership and coordination +Write scope: include/Void/LanguageServer/Build/Providers.hpp; src/Build/CompdbProvider.cpp; include/vls/WorkspaceSession.hpp; src/WorkspaceSession.cpp; src/main.cpp; src/Server.cpp; include/vls/Server.hpp; tests/ProviderProcessTests.cpp; tests/build/CompdbProviderTests.cpp; build.cpp; CMakeLists.txt; tests/CMakeLists.txt; tests/NativeRegistration.cpp +The root exclusively owns these paths. + +## 6. Implementation or investigation approach +Freeze common header following preflight. Implement compdb observation with real immutable inputs and status, retaining last-good historical identity only under the same provider/locator. Route LSP initialize workspaceFolders then rootUri fallback, add/remove and passive settings changes, expose custom voidLanguageServer/providerStatus for a selected workspace/document. Identify incarnation on root re-add, do not reuse old trust or state. Advertise only implemented workspace capabilities. Auto mode prefer existing VBS selector even if broken; deliberate manual provider never silently switches. Allow explicit scoped launcher settings and metadata locators, preserve help/version-only handling, reject bare -- and conflicting choices. Prove edits and file replacements update status through a fresh observation. Keep discovery bounded under admitted roots; do not search environment/user home. + +## 7. Interfaces and data contracts +NEW namespace Void::LanguageServer::Build. Root owns Providers.hpp. ProviderScope contains WorkspaceIdentity workspace, optional absolute exact_database, exact_selector, build_root, producer_cwd (root-bound launcher grants only) and Workspace::ResourceLimitsConfig limits. enum FilePurpose {selection,status,database,response}; read_provider_file(scope,path,purpose,byte_limit) returns expected; provider_file_current(scope,file) revalidates identity. ProviderFile has purpose, logical_path, canonical_path, bytes, content_id, stamp; stamp binds admission root, opened object and selected name. ProviderIssue has string code,message and filesystem::path path. DatabaseInput has const ProviderScope& scope, const ProviderFile& database, optional profile, optional driver; DriverInput holds a workspace/purpose/generation checked Workspace::ToolCheck and Workspace::CompilerDriver, plus known wrapper spellings. import_commands(const DatabaseInput&) returns expected; ImportedCommands has vector contexts, vector dependencies and string revision. ProviderObservation has string provider, optional selection_ticket, optional profile, Generation generation, vector issues and vector inputs; fresh is a generation without blocking issues (row limitations stay in context). observe_vbs(scope, selector_path, optional), observe_compdb(scope, database_path, optional) return ProviderObservation. Root owns latest sequenced publication and revalidation at install. All reads are passive. Concrete spelling in forthcoming header coordinated by root after preflight. + +## 8. Dependencies and integration +Freeze common header for three disjoint agents from shared planner/preflight evidence. Use published BuildGeneration immutable data and capture sequences for installs. Default scan remains passive. Final root performs installation, real consumer observations and regression matrix. + +## 9. Edge cases security and performance +T-PREFLIGHT-007 amendment. Bind each external locator/grant to one explicit launcher-selected root and capture its scoped directory anchors when configuration is installed. Distinguish absence of the selector from dangling/denied/invalid selectors or a missing selected DB/status. Only genuine selector absence permits auto compdb; repeat that negative lookup before installing any fallback, reject a VBS-managed alias as an automatic fallback and keep last-good separate. Assign a sequence before every observation, and compare latest sequence, config revision, trust generation and workspace incarnation for success AND failure before installation; revalidate retained inputs, including selector absence where applicable. Re-adding a root starts a fresh owner. A removed or revoked owner cannot publish late work. Add deterministic tests that introduce the selector between reads, and complete stale work after settings/revocation/removal+re-add. Use a bounded private session status response for errors. +Restart, removal/re-add, broken versus absent native selection, two workspace folders with conflicting locator preferences and root-bound launcher grants; cap workspace/status result sizes, alternatives and issue text. URI aliases, malformed application settings and requests produce typed errors. Preserve deterministic ordering and stderr-only diagnostics. Consumers of provider caches revalidate latest observations before publishing current state. + +## 10. Acceptance criteria +Actual transcripts show two roots choosing distinct providers, direct manual native failure, valid native generation+compdb alternatives, edits/replacements, selection changes and no launch. Zero stdout outside framed protocol. Both build systems register nonzero cases; process, build, install, counts and honest residuals recorded. + +## 11. Verification commands and evidence +Use git status --short --branch, scoped graph coverage plus direct reads, dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only on the owned sources and tests, then link/run the actual Void::Testing suite in a private build subdirectory. Use dev cpp -c clang-format --dry-run --Werror on owned C++ paths. List the cases via --list --no-color. Root owns the two shared build trees. Run integrated native vbs test/install, compare optional CTest, query both generated real DBs using vls --stdio; make missing/failed cases ordinary checks. + +## 12. Constraints and stop conditions +Do not turn an untrusted IDE initialization value into a launcher grant; reject external reads with ambiguous scope. Escalate new protocol/product decisions only if outside existing acceptance; do not delay known passive workflow. + +## 13. Authorization and decisions +D-022,D-025,D-026,D-027; no external side effects or Git mutations beyond prior branch creation. + +## 14. Return format +Root records code/commands, verified capabilities, remaining gates and fresh independent integrated review. diff --git a/docs/agent-workflow/tasks/T-PROVIDER-VBS-006.md b/docs/agent-workflow/tasks/T-PROVIDER-VBS-006.md new file mode 100644 index 0000000..d6cf909 --- /dev/null +++ b/docs/agent-workflow/tasks/T-PROVIDER-VBS-006.md @@ -0,0 +1,49 @@ +# Read selected native VoidBuildSystem editor generations + +Task ID: T-PROVIDER-VBS-006 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975, dirty files authorized. Primary native descriptor build.cpp, optional CMake verification, VoidLibrary main 7d7d23e. T-PLAN-006 verified VBS 6c225c2 selector/status/generations and actual compdb rows. Build/Model.hpp, Workspace/{Configuration,Trust}.hpp and Protocol/Json.hpp are implemented. Root owns build/test registration, CLI, session, docs and integration. No shared tree branch switches, Git mutations, sibling writes, child agents or independent user messages. + +## 2. Objective and deliverables +Implement passive VBS v1 generation observation against current real producer output. Make explicit what today's emitter supplies and what the proposed richer export still requires. + +## 3. Scope and non-goals +v1 input consumer and its tests only. No invoking VBS, description/graph execution, alias shortcuts, lockfile mutation or changes to producer, state machine or CLI. + +## 4. Files to inspect +See .vbs/editor_selection.json, build/native-validation/profiles/debug/editor/status.json and its referenced immutable compile_commands under this workspace only. Read source of committed producer build/tools/vbs-6c225-src/src/Editor/CompDb.cpp (sanitize_profile_dir, emit/status/select logic), T-PLAN-006, roadmap 06 and Build/Model.hpp. + +## 5. Write ownership and coordination +Write scope: src/Build/VbsProvider.cpp; tests/build/VbsProviderTests.cpp +Root owns public header, session, test wiring and shared model. + +## 6. Implementation or investigation approach +Read bounded selection, profile status, immutable DB via scoped file reader. Validate schema_version, ticket, selected tuple, generation component and producer-sanitized profile component, status/profile/entry_count/path consistency; preserve readiness warnings. Use derive-and-verify exact profiles//editor/generations//compile_commands.json underneath an authorized root, never directly trust arbitrary producer pointers or aliases. Empty/reserved ticket can have no generation or retain previous tuple. Valid selected-generation observations recheck both pointers, DB and response dependencies before installation. A stale/invalid status may retain old id/path and omit count. Report explicit stale/missing/invalid/unsupported/ambiguous outcomes. Relative locators follow known producer-cwd or exact authorized build-root association and verified suffix; do not guess server cwd/selector parent or append build prefix twice. Forbid path traversal and misleading suffix-only checks when a supplied absolute or relative pointer actually conflicts. Same ticket may point at a new generation. No nonexistent target/host/MAP/module/retention facts; keep originals. + +## 7. Interfaces and data contracts +NEW namespace Void::LanguageServer::Build. Root owns Providers.hpp. ProviderScope contains WorkspaceIdentity workspace, optional absolute exact_database, exact_selector, build_root, producer_cwd (root-bound launcher grants only) and Workspace::ResourceLimitsConfig limits. enum FilePurpose {selection,status,database,response}; read_provider_file(scope,path,purpose,byte_limit) returns expected; provider_file_current(scope,file) revalidates identity. ProviderFile has purpose, logical_path, canonical_path, bytes, content_id, stamp; stamp binds admission root, opened object and selected name. ProviderIssue has string code,message and filesystem::path path. DatabaseInput has const ProviderScope& scope, const ProviderFile& database, optional profile, optional driver; DriverInput holds a workspace/purpose/generation checked Workspace::ToolCheck and Workspace::CompilerDriver, plus known wrapper spellings. import_commands(const DatabaseInput&) returns expected; ImportedCommands has vector contexts, vector dependencies and string revision. ProviderObservation has string provider, optional selection_ticket, optional profile, Generation generation, vector issues and vector inputs; fresh is a generation without blocking issues (row limitations stay in context). observe_vbs(scope, selector_path, optional), observe_compdb(scope, database_path, optional) return ProviderObservation. Root owns latest sequenced publication and revalidation at install. All reads are passive. Concrete spelling in forthcoming header coordinated by root after preflight. + +## 8. Dependencies and integration +Call import_commands for rows. Root owns latest workspace publication, stale history, CLI/config. Produce only per-observation evidence including ticket/profile, selection+status+db+response file identities; when a coherent healthy read yields a generation keep generation identity sufficiently scoped to profile/build root/compdb/response bytes. Failure data keeps selector authority. Preserve record/observation limits. + +## 9. Edge cases security and performance +T-PREFLIGHT-007 cleared this slice. The actual shared header is include/Void/LanguageServer/Build/Providers.hpp, including FilePurpose::native_database, shared immutable bytes and a distinct warnings list. Reject "." and ".." profile components; require original status.profile equality even if two spelling variants share a slug. Validate the producer's 16 lowercase hex digits and separately bind its database bytes. The preimage of its generation identity includes unavailable producer information. +Synthetic fixtures under private temp only. Include two profiles, idle reservation, stale explicit selection, same-ticket change, mismatched profile, corrupt/dangling immutable reference, alias disagreement, failed/readiness state and no process launch. Preserve valid empty DB as zero rows where producer reports that. Use exact null/missing type handling and unsigned ticket conversion with range failure instead of casts. + +## 10. Acceptance criteria +Nonempty VbsProvider suite covers native state transitions and paths above, including repeated-row alternatives, warning retention, manual invalid current with no alias fallback, absolute+relative forms. Demonstrate passive read on a real VLS-generated native generation after root integration. No claims of complete resolved export/artifact lifetime without a real emitter. + +## 11. Verification commands and evidence +Use git status --short --branch, scoped graph coverage plus direct reads, dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only on the owned sources and tests, then link/run the actual Void::Testing suite in a private build subdirectory. Use dev cpp -c clang-format --dry-run --Werror on owned C++ paths. List the cases via --list --no-color. Root owns the two shared build trees. + +## 12. Constraints and stop conditions +Stop if any required field cannot be determined from the real producer or a change to a sibling repo would be required. Missing rich metadata is a visible limitation, not reason to abort v1 status. + +## 13. Authorization and decisions +Native first-class priority D-025; user authorized C++/VoidLibrary implementation on the separate branch only. Reuse helpers rather than run the producer. + +## 14. Return format +T-PROVIDER-VBS-006 DONE/PARTIAL/BLOCKED, producer fields, supported path rules, actual tests, evidence gaps and integration contract. diff --git a/docs/agent-workflow/tasks/T-REPAIR-PROVIDER-007.md b/docs/agent-workflow/tasks/T-REPAIR-PROVIDER-007.md new file mode 100644 index 0000000..b0f1a53 --- /dev/null +++ b/docs/agent-workflow/tasks/T-REPAIR-PROVIDER-007.md @@ -0,0 +1,49 @@ +# Fix source ownership, independent metadata grants and exact VBS file locators + +Task ID: T-REPAIR-PROVIDER-007 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Reviewer T-REVIEW-PROVIDER-007 reproduced three defects in actual installed/stdin queries on feat/implement-roadmap ca04975. Full integrated provider suite passes 36/36 but misses these. Existing provider preflight covered these ownership/scope boundaries; this is a correction under the approved design. User requests GPT-6.2 family Max and native VBS primary. + +## 2. Objective and deliverables +Complete the remaining importer source path/driver response findings. Root has already corrected independent optional grant failure and VBS trailing slash handling and owns their tests. Implement observable regressions and test through actual session/model. Do not suppress legitimate contexts by dropping entire otherwise valid databases. + +## 3. Scope and non-goals +Passive provider/model code and focused tests. No active compiler process invocation, no shared build wiring or docs, no changes to sibling producer. Preserve strict symlink policy for metadata acquisition and positive/negative evidence checks. + +## 4. Files to inspect +Read original T-PROVIDER-{IO-007,ROWS-007,VBS-006,SESSION-007}, current src/Build/{ProviderFile,CommandImport,VbsProvider,Model}.cpp, include/Void/LanguageServer/Build/{Model,Providers}.hpp, src/WorkspaceSession.cpp, tests/providers/{CommandImportTests,ProviderFileTests,VbsProviderTests}.cpp, tests/workspace/ProviderSessionTests.cpp. Inspect actual Model.cpp prepare_context/BuildGeneration source indices and Documents URI physical identity. Root moved tests/build to tests/providers to support native snapshots. + +## 5. Write ownership and coordination +Write scope: src/Build/ProviderFile.cpp; src/Build/CommandImport.cpp; src/Build/VbsProvider.cpp; src/Build/CompdbProvider.cpp; src/Build/Model.cpp; include/Void/LanguageServer/Build/Model.hpp; include/Void/LanguageServer/Build/Providers.hpp; src/WorkspaceSession.cpp; tests/providers/CommandImportTests.cpp; tests/providers/ProviderFileTests.cpp; tests/providers/VbsProviderTests.cpp; tests/workspace/ProviderSessionTests.cpp +Root has finished its corrections to ProviderFile.cpp and VbsProvider.cpp and releases these to you. Preserve those changes. Do not duplicate their tests. Use configuration/session/input-current propagation only where needed for the importer. All other files including CLI, process tests, both shared builds and docs are root/other owned. Minimize changes and coordinate if a new file is essential. Private build/provider-repair-007 for proof, no staging/commits/branches/network/external messages/further agents. + +## 6. Implementation or investigation approach +For row.file `link/../x.cpp` with `link -> real/sub` and BOTH root/x.cpp and root/real/x.cpp, lexical normalization can publish false ownership. Preserve exact provenance; resolve crossing symlink parent components with trusted scoped metadata only and stable binding/revalidation, or represent uncertain TU as unselectable and retain context data. A model's necessary mapping for key.owning_tu cannot itself manufacture authority; if a resolution is withheld, all model lookups must respect that state. Direct normal rows, genuine missing generated TUs without path ambiguity and intentional equivalent links should not silently bind another file. Positively support simple symlink TU and physical identity when provable; revalidate alias change before installing, bound path work and avoid reading source contents or probing outside workspace authority. Include separate `directory` parent-step case. No fake source mappings or invented tool identities. + +## 7. Interfaces and data contracts +Grant isolation: bind workspace root as mandatory; external exact metadata/build root failures attach to their own grants for the entire settings grant lifetime. Do not repin redirected names automatically on re-add/configure, and do not let unused external compdb/selector/build grants invalidate independently valid VBS or ordinary metadata. Only proven absent native selector may fall through to compdb. Retain real scope limiter, typed independent errors and immutable anchors. Reconsider reuse_provider_scope tests that previously required all grants simultaneously; check returned error for requested route and ordinary route remains available. VbsProvider::locator must distinguish directory names from file pointers, rejecting terminal '/', '/.' or '..' before normalization for both selected_compdb_path and status.compdb_path. Legitimate build directory spellings remain accepted. + +## 8. Dependencies and integration +Root owns final validation/both shared descriptor files/stdin tests plus independent review. Reviewer still reading and may issue additional related requests; contact root before broadening. No change to normal producer wire. Existing new tests under tests/providers are the actual paths. + +## 9. Edge cases security and performance +Prevent opposite failure: do not accidentally permit auto fallback on an unavailable external selector, reopen a newly created external parent, or reinterpret a non-direct/native generation alias. Negative lookups and prior/current generations scoped. Limit file descriptors/storage and work, ensure failed/retargeted path cannot restore prior physical mapping. Distinguish inode/path alias safely where practical. + +## 10. Acceptance criteria +Additional verified checked-driver regressions from the independent reviewer: POSIX double-quoted -I"inc\\q" must preserve an ordinary backslash like typed argv; a missing @later.rsp that then appears invalidates prior partial observation; a workspace lexical -I directory symlink actually leading outside cannot yield typed search authority. Retain bounded negative response evidence through provider+session publication, distinguish missing vs denied, handle retargeting. Extend focused tests for all three. +Prove ambiguous link/../ path does not select innocent root/x.cpp, real/alias result positive if evidence is retained else documented unavailable for ambiguous route; simple stable alias maps appropriate physical TU; changing path during delayed publication cannot make old generation authoritative. Unavailable exact compdb parent + valid native stays ready both explicit and auto; native selector exact parent failure never falls through; directory replacement remains fail-closed for affected route across readd. Selector and status file ending slash/dot refused. Existing VBS, compdb, row, model, session regressions preserved. + +## 11. Verification commands and evidence +Use dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only for changed C++ files, focused runner linked with current sources into private build/provider-repair-007 or coordinate with root to use root-run CMake/VBS. Use dev cpp -c clang-format --dry-run --Werror scoped. Return enough details/root build-ready signal promptly. Record commands/actual exit; require real nonzero cases. + +## 12. Constraints and stop conditions +Stop for scope expansion/new authority or incorrect model-wide assumptions. After two failed repairs give root distinguishing evidence and adjusted hypothesis. Do not demote user features to hide an unsupported alias; preserve honest status. + +## 13. Authorization and decisions +Explicit implementation approval D-022, native priority D-025, confirmed family/Max D-027. Previously independent reviewer gave concrete real failures; root handles final review and release decisions. + +## 14. Return format +T-REPAIR-PROVIDER-007 DONE/PARTIAL/BLOCKED, files, three disposition proofs, test evidence, missed edges and requirements for root tests. Send early stable APIs/build-ready notices. diff --git a/docs/agent-workflow/tasks/T-REPLAY-RECORDING-019.md b/docs/agent-workflow/tasks/T-REPLAY-RECORDING-019.md new file mode 100644 index 0000000..42bd6cf --- /dev/null +++ b/docs/agent-workflow/tasks/T-REPLAY-RECORDING-019.md @@ -0,0 +1,50 @@ +# Retain one verified immutable compiler recording for debugger queries + +Task ID: T-REPLAY-RECORDING-019 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared feat/implement-roadmap ca04975 plus standalone vls_gcc_probe/journal. At Trace.cpp:938–993 replay(path,sequence) opens and validates a whole physical journal and returns all captured source/diagnostics for each call; a DAP connection cannot use that for every stack or source query. The previous trace owner is finished. T-PLAN-DAP-020 confirmed real 17/34 and 22/44 stops at sequences 6,10,21,25 and a fixed process outcome. The journal hash chain and typed compiler event rules already exist. + +## 2. Objective and deliverables +Implement one immutable C++ recording object which validates a bounded journal once, retains the verified prefix, provides bounded event navigation and historical cursor/stack/value queries, and exposes captured source and process outcome. Preserve the old replay CLI/API behavior for all existing cases. The forthcoming DAP service and custom views share this object. + +## 3. Scope and non-goals +Recorded inspection only. No DAP transport, live process/control changes, generalized new compiler record format, re-opening arbitrary source filenames, or claims for unavailable template/constraint/physical facts. + +## 4. Files to inspect +Inspect experiments/frontend/gcc-worker/{Trace.hpp,Trace.cpp,Main.cpp,Supervisor.cpp}, tests/debug/TraceTests.cpp, tests/native/GccSupervisor.py, docs/agent-workflow/tasks/T-GCC-TRACE-019.md, docs/roadmap/{18-live-debugging,19-recorded-replay,20-dap-service,21-inspection-api}.md (resolve actual roadmap 19 filename). Root has real fixed local recordings under build/plan-dap-020/capture-16mqf07g/ with compiler unavailable permitted at replay time. + +## 5. Write ownership and coordination +Write scope: experiments/frontend/gcc-worker/Trace.hpp; experiments/frontend/gcc-worker/Trace.cpp; tests/debug/RecordingTests.cpp +Existing TraceTests.cpp, Supervisor, console CLI, DAP sources and build files remain under other ownership. Preserve their contracts. Private build/replay-recording-019 allowed for benign test inputs. No Git mutations or additional agents. + +## 6. Implementation or investigation approach +Re-use the actual JournalReader/Timeline validation and verified-prefix semantics. During one open from the explicitly supplied file acquire owned source/diagnostics/outcome/verified event transitions. Avoid duplicate parsers or O(event_count * stack_depth) retained per-event snapshots. Index the actual event ordinals/types, frame IDs, active call ancestry/phase/last value as useful; retain time-specific data, including a provisional result preceding a failed leave. Permit a fixed initial decode or bounded in-memory reconstruction consistent with the current 4096-event/1 MiB limits; paging metadata should not rebuild the cursor per item. Expose lookup of the next/previous actual observed integral stops/values without synthesizing calls. A result/source handle retains the recording independent of path replacement or deletion. Never reread the journal when inspecting/stepping. Do not modify the append format or transcript checks. + +## 7. Interfaces and data contracts +NEW vls::gcc::ReplayRecording (exact names to freeze with root): static open(absolute_path) -> expected,string>; event_count(), bounded page of verified event summaries carrying seq/kind/optional frame/parent; cursor_at(seq) containing post-event frames/lastLeave/stop and identity, without copying captured source/diagnostic bytes; recording metadata/status for partial, corrupt, completed/cancelled/failed+exit, immutable source/diagnostics access. Provide historical stage just AFTER event, before any following recorded command; final cursor reflects later authorization/outcome. Digests/nonce/PID are recorded identities, distinct from DAP handles. Retain truthful sourceKind from compiler. Unknown/unavailable, event outside verified prefix, start/past end and cut tails produce explicit outcomes. Keep replay(path,optional_seq) as a compatible wrapper including capture fields. Document any cursor scale limits and support DAP access to source as raw bytes with separate UTF8 validation upstream. + +## 8. Dependencies and integration +The replay consumer needs each observed integer-value event, plus its immediately following matching compiler stop when present. A recorded value in an unattended run is a cursor point, even when the compiler never paused there. Coalesce that value and optional matching stop into one debugger navigation point in the session layer. Preserve both raw verified ordinals in the recording API. Never copy a subsequent action, ack or finish into an earlier event-time state. Keep journal outcome/partial status at the recording level. Actual fixtures have E5 provisional value, E6 stopped, E7 acknowledged, E8 leave returned and E9 outer value. Source bytes last for the recording lifetime; pause-generation references belong to the consumer. +Planner reviewed real journal, returns live stop handshake to separate ownership. Root handles DAP adapters, views and tests on an actual compiler recording. CMake/VBS already compile Trace.cpp. Root will add RecordingTests.cpp to vls_trace_tests. No compiler rebuild or license decision is required. + +## 9. Edge cases security and performance +Existing file/record/stream caps and per-record hash checks stay effective. Add aggregate index/storage/format caps consistent with current producer; never allocate proportional to untrusted claimed file length. Deep nested frames cannot cause quadratic stored memory at open. Distinguish truncation from invalid/corrupt tail, accepted prefix from completion, bad manifest from partial later failure. DAP cursors must be immutable, thread-safe reads, stable after client disconnect/old cursor release, bounded terminal/source copying. Handle binary source (do not convert arbitrary bytes to a JSON string), dirty concurrent append, and no fabricated execution success. + +## 10. Acceptance criteria +The immutable resumed-event detail must retain the acknowledged compiler stop ordinal and action. A recorded step and a continue can otherwise produce identical cursor state after the ack. Compare the real E11 acknowledgement in source17-stepped.vls and source17-every-return.vls, or equivalent exact prefixes, and a journal with command authorization but no ack. Authorization alone must remain pending. +Existing 13 trace and native supervisor tests remain green. New cases: open once then unlink, overwrite, replace path: old recording still returns old inner 17 and outer34; a separately opened newer capture sees 41/82. Repeated concurrent seeks, bounded paging and deep nesting, duplicate/invalid/out-of-range ordinals; authorized command vs actual resumed; failed cleanup after provisional value; manifest-only and corrupt/truncated suffix; source with NUL/invalid UTF-8, missing process outcome. Verify a real four-stop recording durably from parent-provided fixture where feasible. Release exact API early so DAP owner can build. + +## 11. Verification commands and evidence +Run dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only experiments/frontend/gcc-worker/Trace.cpp tests/debug/RecordingTests.cpp. Private linked runner with actual Void libraries allowed. Root re-registers in native+CMake and uses vls_gcc_probe replay on the T-PLAN-DAP-020 actual recordings. clang-format --dry-run on owned paths. Return actual cases and timings. + +## 12. Constraints and stop conditions +Do not implement DAP or alter accepted v1 compiler event authorization. If requirement needs an incompatible recording format or source/privilege decision, report the evidence and complete the independent immutable-reader portions. + +## 13. Authorization and decisions +All roadmap plans authorized D-022, separate branch native VBS D-025, GPT-6.2 Max D-027. T-REPLAY-RECORDING-019 normal read-only artifact usage does not choose an instrumentation technology. No Git staging/release. + +## 14. Return format +T-REPLAY-RECORDING-019 DONE/PARTIAL, frozen API and time/space bounds, real artifacts, record count/seek evidence, actual test results and limitations. Notify root at compilation-ready and release. diff --git a/docs/agent-workflow/tasks/T-REREVIEW-PROVIDER-007.md b/docs/agent-workflow/tasks/T-REREVIEW-PROVIDER-007.md new file mode 100644 index 0000000..055e96c --- /dev/null +++ b/docs/agent-workflow/tasks/T-REREVIEW-PROVIDER-007.md @@ -0,0 +1,48 @@ +# Re-review the provider repairs against actual editor queries + +Task ID: T-REREVIEW-PROVIDER-007 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Fresh independent review of actual shared checkout feat/implement-roadmap at ca04975. Main development is native VoidBuildSystem with CMake secondary. User approved full roadmap and Max GPT-6.2 family, and specifically requires GPT-6.2 Astra at Max for reviews. No review substitution. The provider preflight required pinned grants, genuine negative evidence, prefix/TU verification, and latest-issued publication (see T-PREFLIGHT-007). + +## 2. Objective and deliverables +Re-review the corrected P1/P2 findings from the prior independent review, with priority on actual physical source selection and revalidation after alias/parent replacement. Inspect the changes and run distinguishing checks for every item. Focus on remaining major defects directly on these repair paths. + +## 3. Scope and non-goals +Review acquisition, import, VBS/compdb selection, session semantics, CLI/configuration, build and LSP process integration. Recheck relevant cross-file trust/document/model behavior. Known unrelated upstream JSON precision/range failures have tracked separate ownership. No compiler-patch review, release verdict or implementation edits. + +## 4. Files to inspect +Inspect git diff ca04975 and the actual new untracked files in include/Void/LanguageServer/{Build/Providers.hpp,Support/RegularFile.hpp}, src/Build/{ProviderFile,CommandImport,VbsProvider,CompdbProvider}.cpp, src/WorkspaceSession.cpp, include/vls/{Server,WorkspaceSession}.hpp, src/{main,Server}.cpp, src/Workspace/{Configuration,Trust}.cpp, tests/providers/, tests/workspace/ProviderSessionTests.cpp, tests/ProviderProcessTests.cpp, tests/native/InstalledServer.py, build.cpp, CMakeLists.txt, tests/CMakeLists.txt and tests/NativeRegistration.cpp. Consult individual provider task specs and ACTUAL VoidBuildSystem selector/status generation if a claim depends on the producer. Tests formerly under tests/build moved to tests/providers because VBS excludes directories named build from project snapshots. + +## 5. Write ownership and coordination +Write scope: none +Use only private ignored build/rereview-providers-007 for any benign fixtures or generated verification artifacts. No editing shared sources/docs, builds, branches, commits, sibling checkouts, dependencies, tools or user messages. The root owns build wiring and provider integration. Other agents own the compiler prototype and module work. + +## 6. Implementation or investigation approach +Trace a real request and one failed/superseded request across wire → session → providers → pinned IO → bounded importer → BuildGeneration → publication. Examine source lifetime, exception/outcome, TOCTOU, alias/hardlink/negative lookup, passive prefix-to-origin checking, language/value/settings origins, issue/epoch serialization, workspace and trust reconfiguration, no stale publishing. Try to refute implemented claims using tests and actual local executables. Inspect untracked source directly; a clean tracked diff is insufficient. + +## 7. Interfaces and data contracts +The public contracts are Providers.hpp, Model.hpp, WorkspaceSession.hpp. Status is voidLanguageServer/providerStatus, supports per-workspace scope and optional document. Auto VBS precedence, a dangling/stale selector or missing native generation stays VBS. No automatic trust execution. Immutable revisions scoped to incarnation; unknown role/source remains explicit. Native v1 lacks target/module/role richness, retain unknowns. + +## 8. Dependencies and integration +The prior reviewer reproduced wrong ownership with link/../x.cpp, an unused missing external compdb grant poisoning native, accepted trailing-slash file locators, POSIX double-quoted backslash loss, missing response recreation not invalidating, escaped search paths and an installed validator failing with 17 alternatives. On the repaired shared sources, root ran 22/22 CommandImport and 4/4 actual ProviderProcess tests. CMake registers 41 provider and 16 process cases. Native/integration rerun in progress. Read T-REPAIR-PROVIDER-007 for the contract and inspect CommandPathWalk, the generation identities, scope stamps and latest input rechecks. + +## 9. Edge cases security and performance +Watch resource amplification (nested rows/response files, retained generations or file descriptors), boundary alignment after file rename, root re-add, external exact/build roots and user-origin grants. Verify tests do not accidentally pass with no-op handler, invented context values or shell success. Identify exposed user failures and materially justified fixes, not speculative style churn. Use only ordinary owned fixtures and read-only inspection. + +## 10. Acceptance criteria +Report independent concrete verdict for acquire/import/native/compdb/session/CLI/integration and tests, supported by exact files/lines, reproductions and observed exit codes. Distinguish pre-existing known JSON findings. If a high-priority issue exists, notify root early to begin correction while you review disjoint areas. + +## 11. Verification commands and evidence +git status --short --branch; git diff --check; run build/bootstrap/tests/vls_provider_tests --no-color, vls_workspace_tests --no-color and vls_process_tests --no-color; check native list/installed result if useful. Read build/native-evidence/{providers-installed,provider-regressions-build,provider-repair-cmake}.log; optional targeted proof only under private review dir. No shared builds or compiler experiments. + +## 12. Constraints and stop conditions +Stop if prerequisite prevents factual verdict, report missing evidence or actual runtime error. Do not downgrade or silently substitute model on 429. No merge/release or deployment actions. + +## 13. Authorization and decisions +User D-025/027/029: native VBS, explicit GPT-6.2 Astra at Max, preserve independent reviewer. Passive workspace and provider implementation cleared after amendments. This review is of code and behavior. + +## 14. Return format +T-REREVIEW-PROVIDER-007 READY/CHANGES_REQUIRED/BLOCKED with scoped verdicts, findings highest impact first, evidence/commands and untested paths. Report to root only. diff --git a/docs/agent-workflow/tasks/T-RESEARCH-008.md b/docs/agent-workflow/tasks/T-RESEARCH-008.md new file mode 100644 index 0000000..fb734db --- /dev/null +++ b/docs/agent-workflow/tasks/T-RESEARCH-008.md @@ -0,0 +1,96 @@ +# Establish the actual reflection and module reference for the frontend gate + +Task ID: T-RESEARCH-008 +Role: astra_researcher +Status: READY + +## 1. Context and baseline +/home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975. +The user authorized the full roadmap and selected gpt-6.2-astra at Max for this +research role using the generic runtime. The shell passes 37 cases with GCC 16.2. +Roadmap 08/11/12/17/24 needs compiler evidence independent of the build migration. + +## 2. Objective and deliverables +Run small representative probes with the actual GCC/libstdc++ used by Void and +establish how to exercise the exact candidate frontend. Return observed evidence +of supported and failing cases and a precise tool/source provisioning path. + +## 3. Scope and non-goals +Cover the real Void enum helper, reflection/splices through a named module, an +invalid edit and the candidate tool's identity/availability. Ordinary source +inspection and bounded reference compiler experiments only. Production code, +backend selection, compiler patches, debugger implementation and full LLVM builds +belong to later owned tasks. + +## 4. Files to inspect +Read docs/DEPENDENCIES.md, docs/roadmap/{08-frontend-feasibility,11-cpp-modules, +12-reflection-provenance,17-compiler-debug-instrumentation,24-conformance-performance}.md. +The actual helper is build/bootstrap/_deps/voidlibrary-src/include/Void/Detail/Enum.hpp +at VoidLibrary 7d7d23ec0a6a55d4b30921432fa215b29a29e59b. It implements enum_name, +enum_parse and enum_cast with define_static_array, template for and splices. +Pinned upstream project is bloomberg/clang-p2996 at 562409c7942690d59ea470762515f88f24b16e23. + +## 5. Write ownership and coordination +Write scope: none +This is read-only research across all repositories. Run compiler experiments in +a temporary directory under /tmp kept separate from all checkouts, with new +synthetic sources only. Return fixture text, flags and outputs in the report. +All project source, docs, build trees and global configuration are outside scope. + +## 6. Implementation or investigation approach +1. Confirm compiler paths, versions and actual public header entry points. Create +small valid and broken inputs in the temporary directory and run them through GCC. +2. Instantiate the real helper and check observed results. Exercise a named module +with a separate importer using reflection. Capture the flags needed by installed GCC. +3. Check for a matching candidate from ordinary toolchain discovery and official +upstream source/releases at the pinned revision. Distinguish docs, local tests +and unavailable artifacts. If the exact binary is present, run equivalent probes. +4. Return the smallest reproducible compiler-library gate experiment, candidate +resource prerequisites and whether a product decision is justified by the evidence. + +## 7. Interfaces and data contracts +Record compiler executable/version, language/flag list, standard-library identity, +source header revision, module import order, expected diagnostic or program result, +actual process exit status and any difference from a semantic-query assertion. +Future semantic requests must carry source and context identities. + +## 8. Dependencies and integration +Root owns VBS seed work and source integration. The planner handles foundations. +Your compiler results feed roadmap 08/17 and have independent inputs. Use the +existing active Serena project. For graph queries confirm project and coverage, +then verify important claims in actual sources. Do not switch shared projects. + +## 9. Edge cases security and performance +Keep all compiler processes finite. Use one or two compile jobs at a time. Use the +known GCC directly on the fixtures. Do not execute downloaded binaries, project +scripts or plugins. Public queries may name the public fork and commits only. +Do not browse workspace credentials, dotfiles, ignored caches or unrelated projects. + +## 10. Acceptance criteria +1. Reproducible GCC enum helper checks show the actual observed values/exit status. +2. Named-module success/failure and invalid-edit diagnostics have recorded commands. +3. Exact candidate binary availability, provenance and relevant implementation +evidence from primary sources are distinguished from extrapolation. +4. A concrete next experiment addresses libstdc++ fidelity and actual IDE queries. + +## 11. Verification commands and evidence +From repo root run `dev cpp-gcc -c g++ --version` and use the observed compiler +with `-std=c++26 -freflection` for the enum case. Use the temporary directory as +working directory for module compiles, discovering the required module flag from +the installed compiler. Record complete flags, working directories and observed +exit codes. Do not treat a documentation statement as a compiler test. + +## 12. Constraints and stop conditions +Stop before installing software or consuming substantial disk for a toolchain. +Report unavailable candidate tools/access as missing evidence. A failing reference +case should be retained with the smallest distinguishing check. + +## 13. Authorization and decisions +D-002, D-010, D-011, D-022, D-025, D-027. The user approved investigation and +implementation of the plan. Compiler repairs or a change of backend require a +separate explicit technical decision. No publishing, messaging or installation. + +## 14. Return format +Return T-RESEARCH-008 DONE/PARTIAL/BLOCKED, exact commands/results, artifact +paths, tool revisions and official links, evidence per criterion, unrun checks +and recommendation. Distinguish observed behavior from inference. No child agents. diff --git a/docs/agent-workflow/tasks/T-REVIEW-003.md b/docs/agent-workflow/tasks/T-REVIEW-003.md new file mode 100644 index 0000000..e892202 --- /dev/null +++ b/docs/agent-workflow/tasks/T-REVIEW-003.md @@ -0,0 +1,89 @@ +# Review the first bootstrap with decimal-capable VoidLibrary + +Task ID: T-REVIEW-003 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Working directory /home/faumaray/Projects/VoidLanguageServer on feat/implement-roadmap +at ca04975. Upstream main moved from 9931c5f to 7d7d23ec0a6a55d4b30921432fa215b29a29e59b. +T-REVIEW-002 predates decimal support. Root changed the CLI to reject a bare +`--` with exit 2 after Argparse started accepting it. Both builds pass 37 cases. + +## 2. Objective and deliverables +Independently review the CLI/dependency and LSP numeric-ID boundary against the +original T-001 contract. Return a precise verdict and reproductions of actionable +errors. The previous review left the floating-point branch untested. + +## 3. Scope and non-goals +Cover the bootstrap executable and real dependency behavior. Native build work, +new document/store code, future semantic capabilities and the choice of compiler +are separate assignments. You may verify coverage of the current assertions. + +## 4. Files to inspect +Read docs/agent-workflow/tasks/T-001.md, tasks/T-REVIEW-002.md, REVIEW.md and +VERIFICATION.md for acceptance and prior limits. Inspect the actual diff of +src/main.cpp against ca04975 and the affected src/{Json,Server}.cpp, +include/vls/{Json,Server}.hpp, tests/{JsonTests,JsonCapabilities,ProcessTests}.cpp, +tests/{Registration.cmake,TestSupport.hpp}, cmake/VoidDependency.cmake and +build/bootstrap/_deps/voidlibrary-src/include/Void/Data/StrictJson.hpp. + +## 5. Write ownership and coordination +Write scope: none +All source, task records and output trees belong to others. Use existing binaries +or private /tmp scratch for finite subprocess probes. Keep the active Serena +project. No Git mutations or sibling changes. Return findings to root. + +## 6. Implementation or investigation approach +Check the changed default/explicit CLI modes and stdout/stderr/exit contracts. +Examine how parsed decimal and integer forms reach JSON-RPC request ID handling, +how conversion and range validation affect correlation, and whether any accepted +input yields a reply for another ID. Compare StrictJson's representation with +the protocol requirement. Verify the tested revision from the actual build. +Use graph coverage and source checks with the active project as appropriate. + +## 7. Interfaces and data contracts +vls::parse_json returns expected. vls::request_id accepts a decoded +Json and returns expected,string>. Numeric success must +preserve the signed-32-bit value. Invalid ID returns InvalidRequest with null +correlation. The CLI's help/version are standalone and stdout is protocol-only +in default/stdio mode. Existing framing and lifecycle bounds apply. + +## 8. Dependencies and integration +This review is independent of T-PLAN-002, native-build and compiler experiments. +No implementer owns bootstrap source during this check. Root handles findings +and orders any repair against pending work. Verdict is for the reviewed shell. + +## 9. Edge cases security and performance +Cover signed limits, exponent spellings, invalid types and precision loss. Keep +subprocesses small and bounded. No shell execution of protocol fields or reading +credentials. Do not enable capabilities or change test expectations. + +## 10. Acceptance criteria +1. Verify correct CLI exit and stream behavior for the bare marker and regular modes. +2. Verify numeric identity on the real dependency, including cases the ordinary +suite could miss. Record exact request/response pairs for discrepancies. +3. Report any missing evidence for the original JSON gate and regression checks. + +## 11. Verification commands and evidence +From project root, `git diff ca04975 -- src/main.cpp cmake/VoidDependency.cmake` +and `git -C build/bootstrap/_deps/voidlibrary-src rev-parse HEAD` show the change +and revision. Root ran `dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure` +and the corresponding build/local suite. Both passed all four entries, containing +22 unit, 6 JSON capability and 9 process tests. Use build/bootstrap/vls for +bounded LSP probes and the respective test executables in build/bootstrap/tests/. + +## 12. Constraints and stop conditions +If inputs drift, state exactly what was reviewed. If the dependency lacks exact +number provenance, identify its API limitation and affected values. Do not edit +VoidLibrary or implement a parser. Return promptly on a decisive finding. + +## 13. Authorization and decisions +D-021 follows main and D-022 expands scope. D-027 selects gpt-6.2-astra with +Max for this independent review through the explicitly approved runtime role. +The review has no release, network-write or branch authority. + +## 14. Return format +T-REVIEW-003 READY/CHANGES_REQUIRED/INSUFFICIENT_EVIDENCE. For each finding give +severity, source location, trigger, expected and actual output, recommended fix +and distinguishing regression. Include commands and limits. No child agents. diff --git a/docs/agent-workflow/tasks/T-REVIEW-005.md b/docs/agent-workflow/tasks/T-REVIEW-005.md new file mode 100644 index 0000000..918fda6 --- /dev/null +++ b/docs/agent-workflow/tasks/T-REVIEW-005.md @@ -0,0 +1,48 @@ +# Review the integrated native build, protocol and document synchronization + +Task ID: T-REVIEW-005 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Fresh read-only integrated review on /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975. Native build, dependency preparation, checked Protocol, immutable Documents and real session wiring are present. Two upstream JSON precision/range issues remain. Model and workspace workers have disjoint ongoing edits. Earlier preflight accepted four contracts, prescribed model/session amendments; the second contract check got HTTP 429. This is an actual source/diff review of the completed slices. + +## 2. Objective and deliverables +Return actionable defects and separate verdicts for native preparation/build/registration, protocol/session and documents. Include actual source surrounding each finding and a minimal benign reproducer when practical. Evaluate the amended session contract against its actual wire implementation. Prioritize correctness/time/resource defects affecting current use. + +## 3. Scope and non-goals +Scope is the integrated native, protocol and document/code paths plus the CLI/lifecycle compatibility and their tests. Existing R-003 JSON findings are already tracked; report any new behavior separately. Workspace authority/model/provider internals are separate reviews. Do not evaluate the proposed compiler as a successful backend. + +## 4. Files to inspect +Read tasks/T-NATIVE-PREP.md, T-NATIVE-001.md, T-PROTOCOL-005.md, T-DOCS-003.md and T-SESSION-003.md, the relevant preflight corrections and REVIEW.md. Inspect the actual diff from ca04975, including untracked files under include/Void/LanguageServer/{Protocol,Documents}, src/{Protocol,Documents}, src/Server.cpp, src/DocumentSync.cpp, include/vls, build.cpp, tools/prepare-voidlibrary, tests/native/Preparation.py, tests/{NativeRegistration.cpp,TestSupport.hpp,ProcessTests.cpp,ProtocolEncodingTests.cpp,documents/DocumentTests.cpp}, CMakeLists.txt and tests/CMakeLists.txt. Prior 16-file snapshot is build/goal-baseline-20261127; inspect only owned relevant files. Verify VBS seed src/Main.cpp install and src/Package/Fetch.cpp/src/Provider/Provider.cpp in ignored build/tools/vbs-6c225-src only as needed. + +## 5. Write ownership and coordination +Write scope: none +Read-only shared checkout. No Git mutations, source changes, recompiling the shared native build, concurrent vbs metadata writes, sibling access beyond scoped code, or independent user contact. For benign runtime probes use synthetic temp files and already-built executables. Root owns any fixes. No children. + +## 6. Implementation or investigation approach +Trace ingress through typed envelope and immutable store; check LSP number limits, UTF-8/16 negotiation, null/missing fields, stale version/desync/recovery, observer read races including aliases/ABA, memory accounting incl markers/retained snapshots and incremental CRLF index equivalence. Check stream errors/no partial frame and staged dependency handoff. In preparation, check tracked allowlists, source reuse and staging of immutable generations retained by in-flight builds. Inspect both build definitions and exercise the actual registered process/named tests. Check whether any user-visible native commands/docs overclaim support. Prioritize a short list of material defects. Existing wire precision failures are a separate upstream gate; do not waive them. + +## 7. Interfaces and data contracts +The CLI and stdio session use the typed Protocol adapter, document URI/incarnation bindings and one negotiated encoding. Initial capabilities contain positionEncoding and incremental textDocumentSync only. Root supplies static registration and real vls sibling resolution. VoidLibrary follows upstream main. Candidate build and provider/worker integration are separate. Native install requires the development CLI's dependency-aware install path. Existing second contract verdict was unavailable; verify concrete effects. + +## 8. Dependencies and integration +Evaluate actual files and outputs together. Root ran native built-in seed 6c225c2 debug and independent CMake comparison on main 7d7d23e. The expanded integer/decimal suite exposes the same two failures. The focused real transcripts prove preceding text mutations through subsequent split-scalar failures. Document tests initially exposed stale size validation on mismatched text; root fixed index text_size_ and reran the full checks. Tests/native/Preparation.py also passed. Targeted isolated tests may run alongside work on other disjoint paths. + +## 9. Edge cases security and performance +Bound probes. Use synthetic ASCII/Unicode, regular files and benign references only. Source exclusions include secret env and key material and unrelated caches. Verify typed refusals on limits, aliases, unsuitable file types, stale reads and malformed payloads. Look for library false successes, stale capabilities or resource trust from client metadata. Do not run any project-provided tool or test payload as a command. + +## 10. Acceptance criteria +1. Evidence-based READY, CHANGES_REQUIRED or INSUFFICIENT_EVIDENCE per slice with causal source references. 2. Identify each P0–P2 material defect, narrow correction and distinguishing regression, including whether existing tests miss it. 3. Separate existing upstream JSON and VBS install issues from new defects. 4. Report exact executed commands/outcomes, test coverage limits and any fact that blocks a readiness claim. + +## 11. Verification commands and evidence +git status --short --branch; git diff ca04975 -- src/Server.cpp src/main.cpp include/vls build.cpp CMakeLists.txt tests; direct reads of untracked scopes. Check graph coverage for material files. The integrated executables live under build/native-validation/profiles/debug/out/bin. Run --list and selected tests directly; use dev cpp-gcc -c ctest --test-dir build/bootstrap -L documents --output-on-failure and python3 tests/native/Preparation.py -v if useful. The prepared generation/provenance is under build/voidlibrary/current. Reuse logs build/native-evidence/foundation-native-retest.log and foundation-ctest-retest.log after verifying observed results. + +## 12. Constraints and stop conditions +Stop before source changes, undocumented external permissions or emitting unrelated audits. A 429 or unavailable runtime must be identified as a missing review. Do not produce a merge/release verdict for the full project or require unresolved upstream work to block independent correctness evidence. Do not modify or re-run common metadata producers. + +## 13. Authorization and decisions +User authorized full implementation on the separate branch, primary native VBS, following VoidLibrary main and GPT-6.2 family at Max. This is a fresh Astra reviewer via the approved generic runtime. Root retains integration and all external permissions. + +## 14. Return format +T-REVIEW-005, per-slice verdict, severity/location/trigger/expected/actual and remediation for each actionable defect, actual commands and exit codes, coverage and limits, files changed none. Return early for serious defects. No user messages or children. diff --git a/docs/agent-workflow/tasks/T-REVIEW-DAP-020.md b/docs/agent-workflow/tasks/T-REVIEW-DAP-020.md new file mode 100644 index 0000000..6b22f47 --- /dev/null +++ b/docs/agent-workflow/tasks/T-REVIEW-DAP-020.md @@ -0,0 +1,48 @@ +# Review the integrated C++ replay adapter and inspection service + +Task ID: T-REVIEW-DAP-020 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap, ca04975 plus uncommitted work. The earlier DAP preflight approved lifecycle ordering and integral value mapping and identified invalid UTF-8 source; its paging/control review ended in HTTP 429. A standalone recorded adapter and inspection service now compile. Four DAP subprocess cases pass in CMake. GCC's actual fixture and source path were selected by the launcher. + +## 2. Objective and deliverables +Review the integrated diff against the recorded-debug adapter and inspection contracts. Find any reproducible correctness, privilege, parsing, resource or interoperability defect. Give separate disposition on session projections, control/page lifetimes, and transport. Independent implementation fixes are root-owned. + +## 3. Scope and non-goals +Recorded compiler sessions over private stdio, the new C++ files, build wiring, real journal fixtures and tests. Exclude heavy compiler builds, live-debug design, plugin distribution and broad LSP work. + +## 4. Files to inspect +Read include/vls/debug/inspection/ReplaySession.hpp, src/debug/Fields.hpp, src/debug/inspection/ReplaySession.cpp, src/debug/dap/{Main.cpp,Projection.hpp,Projection.cpp}, experiments/frontend/gcc-worker/{Trace.hpp,Trace.cpp}, tests/debug/DapReplayTests.cpp and build.cpp, CMakeLists.txt, tests/CMakeLists.txt and tests/NativeRegistration.cpp. Original contracts are docs/agent-workflow/tasks/T-{PLAN-DAP-020,PREFLIGHT-DAP-020,DAP-TRANSCRIPTS-020}.md. Inspect protocols at the source lines needed; consult official Microsoft DAP specification for uncertain requirements. + +## 5. Write ownership and coordination +Write scope: none +Only private benign verification material under build/review-dap-020 is permitted. No shared source, repository manifests/workflow, user configurations, Git changes or additional agents. Root is implementing the Python transcripts and final native integration. Report any required change to root. + +## 6. Implementation or investigation approach +Drive the actual build/bootstrap/vls-dap --replay with structured framed requests through isolated subprocesses. Check sequence correlation, duplicate handling, initialization/configuration orders, recorded stop versus other value, declared source availability versus arbitrary disk, positive reference validity and paging. Follow the same actual object from custom seek/session through standard stack/variables. Test official strict semantics; don't infer pass simply from current tests. + +## 7. Interfaces and data contracts +Schema v1 and replay are frozen in T-DAP-TRANSCRIPTS-020 §7. All read pages and seek require sessionId/schemaVersion/generation. Event 5 is provisional inner 17, E6 the real stopped record; E7 acknowledges step, E8 completes inner, E10 holds 34, E11 acknowledges continue. E20/E22 are observed without a compiler stop. Adapter seq, pause generation and compiler sequence are distinct. Raw source bytes may include NUL or invalid UTF-8. Standard frames have no physical source mapping and use line/column zero. + +## 8. Dependencies and integration +Real recordings under tests/debug/fixtures/{integral-17,integral-41,cancelled-41}.vls and the private immutable reader are available. Test source opens from arbitrary cwd, no compiler on PATH. Externally verified live evaluation and compiler changes are separate. Root is preparing current VBS artifacts and will relay if available. + +## 9. Edge cases security and performance +Review captured source bound including 1 MiB expanded JSON, malformed fields, binary source and missing HELLO/empty prefix; no arbitrary path, plugin, shell, executable or debuggee launch. Check stale frame/scopes and page/control generations including seek ABA, deadlines/EOF partial framing, truthful thread/capability state, range and accepted integer representation. Any finding should name what data was actually trusted and a representative input. + +## 10. Acceptance criteria +1. Reproduce a real standard and custom transcript using at least one real journal. 2. Recover any distinct observed edge case or explicitly note the examined behavior. 3. Identify remaining missing live/client gates separately from scoped defects. 4. Supply suggested local correction and distinguishing regression for each confirmed defect. + +## 11. Verification commands and evidence +From the root use build/bootstrap/tests/vls_dap_tests --no-color and --list --no-color. Use build/bootstrap/vls_gcc_probe replay "$PWD/tests/debug/fixtures/integral-17.vls" 6 or 8 for ground truth. Invoke tests/native/DapReplay.py only once available, or a private bounded Python stdio transcript. Never relaunch compiler builds or mutate the shared VBS selector during review. + +## 12. Constraints and stop conditions +Inspect the current files directly; prior plans and summaries are evidence pointers. Stop this assignment if new source ownership or a scope expansion is required, and send the issue to root. No external messages or commits. Perform only this independent review. + +## 13. Authorization and decisions +Full implementation D-022, separate branch, native D-025. Execute as generic GPT-6.2 Astra at Max per D-027/029; user specifically requests same-family maximum effort on reviews. + +## 14. Return format +T-REVIEW-DAP-020 READY or CHANGES_REQUIRED, outcomes per component, priority, paths/lines, actual reproduction and unverified integration gates. Send early concrete findings; no subagents. diff --git a/docs/agent-workflow/tasks/T-REVIEW-GCC-019.md b/docs/agent-workflow/tasks/T-REVIEW-GCC-019.md new file mode 100644 index 0000000..0f575d3 --- /dev/null +++ b/docs/agent-workflow/tasks/T-REVIEW-GCC-019.md @@ -0,0 +1,49 @@ +# Review the integrated GCC occurrence, evaluator, supervisor and replay prototype + +Task ID: T-REVIEW-GCC-019 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Fresh independent reviewer requested at GPT-6.2 Astra Max under D-029. Shared repo feat/implement-roadmap ca04975. D-030 covers local GCC16 worker/patches. GCC 0001/0002 built from verified release. Root and separate workers integrated sealed ELF leaf, C++ supervisor, trace and bounded real tests. The current user explicitly asks about stock vs custom compiler: keep claims limited to demonstrated distinctions. + +## 2. Objective and deliverables +This independent retry follows an HTTP 429 before review. A new separate stock GDB experiment observed nested returns on the installed GCC and has its own fixture. It does not supersede the reviewed patches or require expanding this review. Primary native and comparison builds now include the trace suite. +Independently review actual compiler patches, launch/control/journal/state provenance, direct IDE physical token and observed declaration evidence. Run tests or focused read-only distinguishing cases. Return actionable findings and slice verdicts for local prototype readiness and what remains before LSP/DAP/public exposure. + +## 3. Scope and non-goals +Read-only assessment of local GCC patches and experimental packages. No changes to compiler or shared integration, production/backend/license decisions or user messages. Exclude ongoing provider remediation (independent assignment). + +## 4. Files to inspect +Read compiler-patches/gcc-16.2.0/{0001-evaluator-events,0002-ide-occurrences}.patch, experiments/frontend/gcc-worker/{Leaf,Main,Supervisor,Trace}.{hpp,cpp} as present, tests/corpus/frontend/{verify-gcc-events,verify-gcc-ide}.py, tests/debug/TraceTests.cpp, tests/native/{GccLeaf,GccSupervisor}.py, T-PREFLIGHT-GCC-008, T-GCC-{IDE-008,LEAF-009,SUPERVISOR-018,TRACE-019}.md, actual GCC16.2 sources for the relevant hooks, plus root logs listed below. + +## 5. Write ownership and coordination +Write scope: none +Use only private ignored build/review-gcc-019 for ordinary isolated fixtures. No editing shared sources/builds, compiler or symlinks, Git, siblings, deployments, network sends, additional agents or direct user questions. + +## 6. Implementation or investigation approach +Inspect the live acquisition→hello→pause→one-use command→echo→next event and terminal paths and verify what is saved on cancellation, failure, killed leader, slow client and truncation. Ensure frame copies, identity and revision, journal durability/integrity, timestamp/sequence bounds and partial projection match. Independently evaluate physical source mapping, templates/macros/line directives/splices/declaration-only and reused GCC UID lifetime. Reconcile public statements with actual behavior of ordinary GCC16 vs patched hooks. Validate SDL handling of control FDs/seals, CPU/AS caps, input snapshot, diagnostic locations, stale commands and no AST pointer crossing. Use benign project-owned sources to distinguish defects. + +## 7. Interfaces and data contracts +Current CLI vls_gcc_probe run COMPILER SHA256 SOURCE NEW_TRACE [--step] and replay TRACE [SEQUENCE]. Leaf fixed args no standard includes, controlled C++ fixture. Integration is currently limited to local probe; actual language server exposes passive providers. Verify frontendEnd vs wait, SIGPIPE/disconnect and control input liveness, replay continues after removal of source/compiler. Review combined patch first then independently verify known observations. + +## 8. Dependencies and integration +Root built build/bootstrap/vls_gcc_probe and stand-alone under build/gcc-leaf-tests. Root direct GCC harness for 0002 verifies nested/same-line fields/calls, declaration vs definition and Unicode display columns. Root's native/GccSupervisor test just passed real live/edited/cancel/replay and adverse bounded ordinary process tests. tests/debug has 13 cases. Native/CMake registrations are being repeated. Other agents exposed code but their summaries are not grounds for acceptance. + +## 9. Edge cases security and performance +Keep test resource lifetime bounded; do not launch untrusted arbitrary project input or inspect unrelated storage, do not build the compiler. For corruption and protocol cases use finite synthetic data/benign local binaries; no vulnerabilities/exploits against host or external projects. Focus on materially observable correctness, explicit unavailable evidence, reproducibility and test holes. + +## 10. Acceptance criteria +Return independent READY/CHANGES_REQUIRED for 0001 scalar/stop, 0002 occurrence/definition, sealed leaf, supervisor, immutable journal/replay, and suitability to progress toward scope-approved further gates. State critical defects, real paths/lines/test input+expected/actual/evidence, missing compiler capabilities vs genuine implementation bugs and recommended minimal repairs. + +## 11. Verification commands and evidence +git status --short --branch, git diff --check, direct inspect untracked files. dev cpp-gcc -c python3 tests/corpus/frontend/verify-gcc-ide.py --cc1plus $PWD/build/gcc-gate/compiler-build/gcc/cc1plus and same for verify-gcc-events.py, use the private binary and bounded harness. dev cpp-gcc -c python3 tests/native/GccSupervisor.py --probe $PWD/build/bootstrap/vls_gcc_probe --cc1plus $PWD/build/gcc-gate/evaluator-only/cc1plus; run build/gcc-trace-tests/vls_trace_tests --no-color. Inspect build/gcc-gate/{leaf-retest,observed-ide,observed-events,supervisor-runtime,trace-focused}.log. Capture actual nonzero/zero test evidence. + +## 12. Constraints and stop conditions +Stop for necessary external operation or code edit. If runtime rate-limits return blocked review, not a READY claim. Root owns fixes. Report urgent P0/P1 while continuing independent portions. + +## 13. Authorization and decisions +User D-027/D-029 require explicitly configured GPT-6.2 Astra at Max for review, D-030 permits only local compiler experiments, licensing and distribution deferred. No push/release. + +## 14. Return format +T-REVIEW-GCC-019 READY/CHANGES_REQUIRED/BLOCKED, highest impact findings with reproduction+source then slice verdicts, commands/results and residual limitations. Notify parent only. diff --git a/docs/agent-workflow/tasks/T-REVIEW-PROVIDER-007.md b/docs/agent-workflow/tasks/T-REVIEW-PROVIDER-007.md new file mode 100644 index 0000000..760e9e3 --- /dev/null +++ b/docs/agent-workflow/tasks/T-REVIEW-PROVIDER-007.md @@ -0,0 +1,48 @@ +# Review the integrated passive providers and workspace status + +Task ID: T-REVIEW-PROVIDER-007 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +Fresh independent review of actual shared checkout feat/implement-roadmap at ca04975. Main development is native VoidBuildSystem with CMake secondary. User approved full roadmap and Max GPT-6.2 family, and specifically requires GPT-6.2 Astra at Max for reviews. No review substitution. The provider preflight required pinned grants, genuine negative evidence, prefix/TU verification, and latest-issued publication (see T-PREFLIGHT-007). + +## 2. Objective and deliverables +Perform a defect-oriented review of the integrated passive VBS and compile-commands providers including wire dispatch. Report actionable P0/P1/P2, with minimal benign distinguishing test for each and exact code locations. Provide early high-priority findings then READY/CHANGES_REQUIRED for this slice. + +## 3. Scope and non-goals +Review acquisition, import, VBS/compdb selection, session semantics, CLI/configuration, build and LSP process integration. Recheck relevant cross-file trust/document/model behavior. Known unrelated upstream JSON precision/range failures have tracked separate ownership. No compiler-patch review, release verdict or implementation edits. + +## 4. Files to inspect +Inspect git diff ca04975 and the actual new untracked files in include/Void/LanguageServer/{Build/Providers.hpp,Support/RegularFile.hpp}, src/Build/{ProviderFile,CommandImport,VbsProvider,CompdbProvider}.cpp, src/WorkspaceSession.cpp, include/vls/{Server,WorkspaceSession}.hpp, src/{main,Server}.cpp, src/Workspace/{Configuration,Trust}.cpp, tests/providers/, tests/workspace/ProviderSessionTests.cpp, tests/ProviderProcessTests.cpp, tests/native/InstalledServer.py, build.cpp, CMakeLists.txt, tests/CMakeLists.txt and tests/NativeRegistration.cpp. Consult individual provider task specs and ACTUAL VoidBuildSystem selector/status generation if a claim depends on the producer. Tests formerly under tests/build moved to tests/providers because VBS excludes directories named build from project snapshots. + +## 5. Write ownership and coordination +Write scope: none +Use only private ignored build/review-providers-007 for any benign fixtures or generated verification artifacts. No editing shared sources/docs, builds, branches, commits, sibling checkouts, dependencies, tools or user messages. Other active agents own GCC only. + +## 6. Implementation or investigation approach +Trace a real request and one failed/superseded request across wire → session → providers → pinned IO → bounded importer → BuildGeneration → publication. Examine source lifetime, exception/outcome, TOCTOU, alias/hardlink/negative lookup, passive prefix-to-origin checking, language/value/settings origins, issue/epoch serialization, workspace and trust reconfiguration, no stale publishing. Try to refute implemented claims using tests and actual local executables. Inspect untracked source directly; a clean tracked diff is insufficient. + +## 7. Interfaces and data contracts +The public contracts are Providers.hpp, Model.hpp, WorkspaceSession.hpp. Status is voidLanguageServer/providerStatus, supports per-workspace scope and optional document. Auto VBS precedence, a dangling/stale selector or missing native generation stays VBS. No automatic trust execution. Immutable revisions scoped to incarnation; unknown role/source remains explicit. Native v1 lacks target/module/role richness, retain unknowns. + +## 8. Dependencies and integration +Root integrated both build/test systems. Last native and CMake inventories each contain 155 bodies: 29 protocol, 14 process, 22 documents, 28 workspace, 18 model, 36 providers, 8 JSON. Only two independently known numeric tests failed. Native install from empty PATH/cwd produced correct VBS36 and compdb58 status for real main.cpp. Active source owner released latest WorkspaceSession immediately after tests; root repeats both builds on final integration. Review actual code rather than relying on this accounting. + +## 9. Edge cases security and performance +Watch resource amplification (nested rows/response files, retained generations or file descriptors), boundary alignment after file rename, root re-add, external exact/build roots and user-origin grants. Verify tests do not accidentally pass with no-op handler, invented context values or shell success. Identify exposed user failures and materially justified fixes, not speculative style churn. Use only ordinary owned fixtures and read-only inspection. + +## 10. Acceptance criteria +Report independent concrete verdict for acquire/import/native/compdb/session/CLI/integration and tests, supported by exact files/lines, reproductions and observed exit codes. Distinguish pre-existing known JSON findings. If a high-priority issue exists, notify root early to begin correction while you review disjoint areas. + +## 11. Verification commands and evidence +git status --short --branch; git diff --check; run build/bootstrap/tests/vls_provider_tests --no-color, vls_workspace_tests --no-color and vls_process_tests --no-color; check native list/installed result if useful. Read build/native-evidence/providers-{native-final,ctest-final,installed}.log; optional targeted proof only under private review dir. No shared builds or compiler experiments. + +## 12. Constraints and stop conditions +Stop if prerequisite prevents factual verdict, report missing evidence or actual runtime error. Do not downgrade or silently substitute model on 429. No merge/release or deployment actions. + +## 13. Authorization and decisions +User D-025/027/029: native VBS, explicit GPT-6.2 Astra at Max, preserve independent reviewer. Passive workspace and provider implementation cleared after amendments. This review is of code and behavior. + +## 14. Return format +T-REVIEW-PROVIDER-007 READY/CHANGES_REQUIRED/BLOCKED with scoped verdicts, findings highest impact first, evidence/commands and untested paths. Report to root only. diff --git a/docs/agent-workflow/tasks/T-REVIEW-SEMANTIC-013.md b/docs/agent-workflow/tasks/T-REVIEW-SEMANTIC-013.md new file mode 100644 index 0000000..6c347d9 --- /dev/null +++ b/docs/agent-workflow/tasks/T-REVIEW-SEMANTIC-013.md @@ -0,0 +1,51 @@ +# Review stock GCC diagnostic and module-planning integration + +Task ID: T-REVIEW-SEMANTIC-013 +Role: astra_reviewer +Status: READY + +## 1. Context and baseline +November 28 retry on feat/implement-roadmap, HEAD ca04975. The original code remains in the working tree. Both builds now run 266 C++ cases, with only two known JSON number failures. The native and comparison executables passed the real stock GCC stdio corpus. This retry retains the original SARIF decoder and module planner review scope. The root is implementing DAP independently; its files are outside this review. +The shared branch feat/implement-roadmap at ca04975 now has a C++ GCC16 SARIF adapter and P1689 module planner. Native VBS and CMake passed 210 inventoried C++ cases apart from two already recorded JSON precision/range cases. A native real GCC run applied the adapter to the actual DocumentSnapshot.cpp. The module owner released a final 21st case and claims_complete after that run. Both components are data-only (no compiler execution in these library functions). + +## 2. Objective and deliverables +Independently review the integrated code, normal registrations and cross-component correctness; prioritize demonstrable wrong editor ranges, erroneous clean results, incorrect graph readiness/order or stale CMI reuse. Return concrete findings, severity and realistic distinguishing tests. Verify newly authored code, not worker summaries. + +## 3. Scope and non-goals +Read-only focused postimplementation review of the two components below, their fixture evidence and registration. No workspace/provider permission or private compiler/OS supervisor review; no unrelated repository audit. No user contact, subagents, external actions or changes to source. + +## 4. Files to inspect +Read docs/agent-workflow/tasks/T-{DIAGNOSTIC-SARIF-013,MODULE-GRAPH-011}.md and preflight amendments. Inspect include/vls/semantic/Diagnostics.hpp, src/semantic/Diagnostics.cpp, tests/semantic/{DiagnosticTests,GccDiagnosticFixture}.cpp, tests/corpus/frontend/verify-stock-diagnostics.py, include/vls/modules/ModuleGraph.hpp, src/modules/ModuleGraph.cpp, tests/modules/ModuleGraphTests.cpp, build.cpp, tests/NativeRegistration.cpp, CMakeLists.txt, tests/CMakeLists.txt. Compare with existing Docs snapshots and Build model, and actual GCC report examples under build/gcc-gate/{queries,constraint}.sarif. Use git diff plus actual untracked files. The separate real module-corpus bridge is still owned and in progress, so defer its final review. + +## 5. Write ownership and coordination +Write scope: none +Use only a private ignored build/review-semantic-013 directory for optional ephemeral benign source fixtures. No tracked changes, running VBS discovery, Git operations that mutate state, broad index of build artifacts or integration builds. + +## 6. Implementation or investigation approach +Trace source/identity and all conditions required to admit a complete result. Inspect exact variant handling, unique expected artifact/RUN, traceable location policy, false positives at end-of-line, tabs and BOM, valid runner failures, estimate actual bounded work. For modules, distinguish absolute verified output/cwd, true incidence of complete scanned claims, partial graph, census changes, header info and live consumer set. Reuse existing actual data and deterministic controlled test mutations when testing. Interpret all claims against the reviewed task contracts. + +## 7. Interfaces and data contracts +Public APIs decode_gcc_diagnostics, decode_scan and build_module_plan. Their caller must provide actual run and input identities, source-origin evidence, and an explicit validated module domain/census. A caller omitting required evidence should get an explicit limitation. Identify mistakes within that contract rather than treating receipt generation as implemented. Project entries are still passive in stdio. Providers already reviewed independently; do not re-audit them here. + +## 8. Dependencies and integration +For the retry, the module bridge is now released and verified, superseding the earlier deferral in §4. Include tests/modules/GccScanFixture.cpp and tests/corpus/modules/verify.py and the final 21-case ModuleGraph. Stock GCC and the native helper passed all 33 observations; biased DAG detail→api→topology→importer and failed-with-rule status came from the C++ planner. The diagnostics fixture can also run with --isolated-inputs, and uses the new checked compiler-context lease. Assess only this fixture as a consumer; WorkspaceSession implementation has a separate owner. The original review assignment returned HTTP 429 before examining the files. No previous implementation or review role for this assignment. +Root and module worker are validating target integration. You may run build/module-graph-011/module-graph-tests and build/bootstrap/tests/vls_diagnostic_tests or execute the standalone user-selected stock GCC corpus using its fixed flags. CMake/native may be recompiling the last header delta. Check actual timestamps/binary state if relying on behavior. + +## 9. Edge cases security and performance +Watch for stale and missing evidence, scope of operation, numeric precision, catalog collision, deterministic limits, accidentally wrong errors/clears or silent resource amplification. Bound any local test data. No active project/compiler invocation other than explicit fixed test fixtures. No new UX/release requirements. + +## 10. Acceptance criteria +Return READY only when the actual integrated files and affected contracts have been read. Otherwise identify file:line, concrete failing input, observed vs expected and smallest recommended correction. Distinguish real and unit verification, report which artifact you used. Treat a pending bridge or a separately documented upstream limitation as such. + +## 11. Verification commands and evidence +From the repository root run `build/bootstrap/tests/vls_diagnostic_tests --no-color` and `build/bootstrap/tests/vls_module_tests --no-color`. These executables currently register 26 and 21 tests. The two original focused contracts and the immutable module planner are available in the shared worktree. The current stock caller's evidence is in `build/stock-editor/final-installed-editor.log`; review its interface to the decoder if a finding depends on caller behavior. Compiler execution for this review is optional and restricted to benign fixtures. +Permitted checks: build/bootstrap/tests/vls_diagnostic_tests --no-color; build/module-graph-011/module-graph-tests --no-color; dev cpp-gcc -c python3 -B tests/corpus/frontend/verify-stock-diagnostics.py --fixture build/bootstrap/tests/vls_gcc_diagnostic_fixture --database build/native-validation/profiles/debug/editor/generations/b7da5a9f204361f4/compile_commands.json. All are from the repository root. Use scoped syntax/probes if informative. + +## 12. Constraints and stop conditions +Stop and ask root for ownership ambiguity or major scope change. If provider/serializer changes might be needed, report a concise dependency; don't edit it or repeat the previous provider review. Keep separate responsibilities for compiler preparation/guards and the data adapter. + +## 13. Authorization and decisions +Implementation D-022, native VBS D-025, GPT-6.2 Astra Max review D-027/029, optional local compiler feasibility D-028/030. No staging or deployment. + +## 14. Return format +T-REVIEW-SEMANTIC-013 READY or CHANGES_REQUIRED per component, findings first with priorities, observations and commands, outstanding integration gates. Send confirmed actionable findings early. diff --git a/docs/agent-workflow/tasks/T-SEMANTIC-LEASE-009.md b/docs/agent-workflow/tasks/T-SEMANTIC-LEASE-009.md new file mode 100644 index 0000000..8293bcd --- /dev/null +++ b/docs/agent-workflow/tasks/T-SEMANTIC-LEASE-009.md @@ -0,0 +1,50 @@ +# Acquire and revalidate a real compiler context for one editor document + +Task ID: T-SEMANTIC-LEASE-009 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared feat/implement-roadmap ca04975, native VBS primary and real compile_commands support. T-PLAN-SEMANTICS-010 observed the installed native row and stable context model. WorkspaceSession::provider_status currently retains lastGood JSON and creates short-lived SelectionState. Recent root repairs fenced URI selection and optional grants. Stock GCC on the real DocumentSnapshot.cpp row gives valid diagnostics. No stdio semantic operations run yet. + +## 2. Objective and deliverables +Implement a reusable C++ editor-context lease for the future stock diagnostics worker. A caller with an explicitly opted-in launcher driver gets the actual selected TU generation, its checked normalized invocation and ordered command, immutable provider evidence, and a validity check against the workspace/configuration/authority/document route. Repeated unchanged requests preserve Selection identity. Failures carry actionable typed readiness. + +## 3. Scope and non-goals +Only semantic context acquisition, reuse and revocation, not frontend execution or current on-disk file contents. Preserve passive provider status behavior and do not add CLI options/LSP capabilities. The semantic provider may check a driver specifically selected by the launcher, never auto-pick a row executable. + +## 4. Files to inspect +Inspect include/vls/WorkspaceSession.hpp, src/WorkspaceSession.cpp, include/Void/LanguageServer/Build/{Model,Providers}.hpp, src/Build/{Model,CompdbProvider,VbsProvider,CommandImport,ProviderFile}.cpp, include/Void/LanguageServer/Workspace/{Trust,Configuration}.hpp, src/Workspace/Trust.cpp, tests/workspace/ProviderSessionTests.cpp and tests/providers/CommandImportTests.cpp. Use actual revocation, directory and URI semantics. Root has repaired nonexistent '..' traversal and separately verifies earlier provider review findings. + +## 5. Write ownership and coordination +Write scope: include/vls/WorkspaceSession.hpp; src/WorkspaceSession.cpp; tests/workspace/SemanticLeaseTests.cpp +Shared checkout, no other writes. Root serializes the public interface and owns build registration, actual subprocess/corpus, docs and CLI. Preserve all current edits; no staging, branches, dependencies, further agents or user contact. Private build/semantic-lease-009 for verification. + +## 6. Implementation or investigation approach +Reuse WorkspaceSession observation, exact FilePurpose bindings, checked alias/absent-selector revalidation and the existing Build::SelectionState and Workspace::TrustPolicy. Scope opt-in driver to a single explicit launcher workspace. Initial caller grants must be backed by root/purpose/executable configuration and current file identity; project paths/preferences cannot approve. Classifier must receive a real DriverInput for the exact selected driver and core wrappers from licensed settings. A lease supplies execution data, not authority to run arbitrary programs; separately approved frontend/toolchain and bound input view are later dispatch prerequisites. Pin a driver once per new trusted generation. Re-check a recorded pin thereafter; never auto-repin a changed executable. + +## 7. Interfaces and data contracts +NEW WorkspaceSession::acquire_semantic_context(document_uri, optional_workspace_uri, selected_driver) and method to validate a returned lease. Freeze exact names/header early. Selected_driver comprises launcher-selected absolute executable and declared driver family; check identity + operation+root+generation. Lease retains Build::Generation, Build::Selection, shared lifetime for per-file SelectionState, provider stamps/negative fallback, exact checked driver, config/trust/incarnation and document logical→physical binding. Encapsulate mutable owner/validation state. Distinguish unavailable/disabled/no-command/wrong-command/superseded via typed outcomes. Cached selected pointer must remain identical on genuinely equivalent observations. Concurrent independent documents may both succeed; one operation or passive status refresh for B must not gratuitously supersede a still valid read for A. Bound retained cache entries; eviction invalidates or degrades safely. + +## 8. Dependencies and integration +Choose the passive ContextKey over all rows before checking the selected driver's normalized command. A compatible later row cannot substitute for an unusable active row. The root owns the separate checked source-language proof in CommandImport; a lease alone does not make diagnostics available. Expose the monotonic settings generation used by AnalysisInputs independently of normal status issuance. +WorkspaceSession remains sole owner of logical folder configuration and trust. Root handles CLI and integration. Subsequent source/diagnostic workers consume only validated immutable lease; don't synthesize missing standard-library/prerequisite/target metadata. CMake and VBS already include WorkspaceSession.cpp. Agent uses dedicated tests file, root adds to the workspace target. + +## 9. Edge cases security and performance +Keep filesystem reads/driver hash work outside global mutex. At installation compare root object/config/trust and latest applicable observation; current successes and failures obey ordering. Physical aliases/negative responses, invalid native precedence and explicit driver identity replacements invalidate old lease. No ABA after root removal/re-add; no previous last-good admission. Avoid unbounded map growth for arbitrary document paths; return typed saturation or evict. Returned object lifetime must remain safe across shutdown and concurrent use. + +## 10. Acceptance criteria +Reconcile an internal driver revocation from TrustPolicy::check_tool with the owning folder's generation under the incarnation guard. A replaced driver A invalidates old leases while an independently approved unchanged driver B and passive status recover without settings reload. Retain whether the request supplied an explicit workspace; re-evaluate implicit routing when nested folders change at acquisition and validation, with an explicitly selected outer folder as a control. Identical-byte DB replacement or a changed selector ticket must invalidate old evidence despite a matching content revision. An invalidated lease cannot revive on A→B→A; a fresh lease may use the new evidence. Test competing driver rows with different defines and stability of the returned configuration generation across ordinary status. +Prove a root-approved native row and compile database row return correctly normalized command via non-executed benign fixture, unapproved/mismatched/replaced driver returns unready, status cannot promote a pin, one selected pointer survives unchanged lease re-acquisition/status, plan refresh/settings change/driver revocation/root removal/stale selector/alias retarget lose eligibility, commands for two documents independent, missing @file-then-creation changes result. Include deterministic concurrency, cache limits, real populated context counts; no requirement that global project metadata be complete for the diagnostic-only lease. + +## 11. Verification commands and evidence +From repo root run dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only src/WorkspaceSession.cpp tests/workspace/SemanticLeaseTests.cpp. Root registers case suite with native VBS and comparison CMake. Private linked Void::Testing executable permitted. Return actual test bodies and outcomes. Directly reference the existing API implementation, not hypothetical flags. + +## 12. Constraints and stop conditions +Do not execute the driver, invoke VBS or advertise LSP features. Isolate authority generation changes and never pass status-only data as a semantic ticket. Stop and contact root for necessary changes outside exclusive files. C++ model/backend/license decision remains with user. + +## 13. Authorization and decisions +Approved roadmap 05/06/07/09, D-025 VBS primary and D-027 GPT-6.2 Max. Fits D-028/030 isolated derived compiler evidence without selecting a production engine. No Git or sibling actions. + +## 14. Return format +T-SEMANTIC-LEASE-009 DONE/PARTIAL with exact API, files, race/stability/expiry proof, registration counts and limitations. Notify root when interface is stable. diff --git a/docs/agent-workflow/tasks/T-SESSION-003.md b/docs/agent-workflow/tasks/T-SESSION-003.md new file mode 100644 index 0000000..ff7a1e7 --- /dev/null +++ b/docs/agent-workflow/tasks/T-SESSION-003.md @@ -0,0 +1,51 @@ +# Connect negotiated incremental synchronization to the stdio session + +Task ID: T-SESSION-003 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Root integration on feat/implement-roadmap at ca04975 with existing CLI/lifecycle and native build. The current server ignores notifications other than exit, concatenates response JSON and advertises empty capabilities. Document and Protocol owners have separate source ownership. + +## 2. Objective and deliverables +Connect one document store to each LSP session. Serialize response objects through the checked Protocol writer. Provide actual process tests that distinguish a working edit handler from a no-op. + +## 3. Scope and non-goals +Root owns this integration. Do not add editor semantics or compiler diagnostics. A malformed notification may emit bounded stderr diagnostics. It never receives a protocol response. + +## 4. Files to inspect +Inspect src/Server.cpp, include/vls/Server.hpp, tests/{TestSupport.hpp,LifecycleTests.cpp,ProcessTests.cpp}, include/Void/LanguageServer/{Protocol,Documents}, build.cpp, tests/CMakeLists.txt, CMakeLists.txt and T-PREFLIGHT-004. + +## 5. Write ownership and coordination +Write scope: src/Server.cpp; src/DocumentSync.cpp; include/vls/Server.hpp; include/vls/DocumentSync.hpp; tests/TestSupport.hpp; tests/LifecycleTests.cpp; tests/ProcessTests.cpp; build.cpp; tests/CMakeLists.txt; CMakeLists.txt +Root owns these files. Share read-only early interfaces with the Documents and Protocol owners. Integrate after their handoffs. + +## 6. Implementation or investigation approach +Negotiate the first supported client positionEncoding, default UTF-16, supporting UTF-8 and UTF-16. Fix encoding before admitting overlays. On successful initialization advertise just positionEncoding and textDocumentSync openClose=true/change=2. Dispatch didOpen, didChange and didClose only during running state. Validate textDocument objects, URIs and full change arrays. Reserve/copy only bounded arrays. Report a malformed event in a known URI via mark_desynchronized even if the enclosing version is absent or stale. Preserve the original text if any later edit fails. Treat a missing range as full replacement; reject a present null or malformed range. Validate an optional rangeLength as LSP uinteger if supplied; it is deprecated and does not replace validating range coordinates. Empty contentChanges is passed to the document contract or marked malformed if unsupported. + +## 7. Interfaces and data contracts +Wire versions use signed32 LSP integers. Position components and rangeLength use unsigned LSP integers 0..INT32_MAX, including before any document line clamp. Accept an integer only when its decoded value is representable and classifiable under the upstream numeric contract. The open upstream numeric-spelling problem is retained as an explicit gate. Treat known document identity as sufficient to mark the barrier even when payload/version parsing fails. Preserve stdout protocol-only even for errors, notifications or fatal encoding failures. Construct typed success/error objects with request_id_json. On encoding failure use a checked InternalError with a safely representable original ID or close before any write; do not emit partial frames or uncorrelated success. + +## 8. Dependencies and integration +DocumentStore open/apply_changes/close/mark_desynchronized report typed errors. The root coordinates the single canonical Protocol translation units and legacy compatibility headers, adds actual document and test sources to native+CMake builds. Future semantic requests reuse the same store. No process tool authorization or frontend work is part of this integration. + +## 9. Edge cases security and performance +Do not echo raw source text from malformed notifications. Keep diagnostics bounded by choosing fixed categories or bounded messages. Reject 2147483648 as a position before clamping; do not partially publish an edit batch on a malformed event. Preserve prior response-envelope, malformed input, pre-initialize/shutdown/exit handling and stream-error exit codes. + +## 10. Acceptance criteria +1. Validate negotiated UTF-8 and default/supported UTF-16 as well as capabilities through actual subprocess frames. +2. Open a, replace it with an astral scalar, attempt an edit at column 1 and observe the split-scalar diagnostic. Run for UTF-8 and UTF-16. Verify the notifications produce no stdout frames and shutdown/exit remain correct. +3. Use null/malformed range in a later event or invalid uinteger to mark a known document unavailable; a stale full replacement and ranged edit cannot recover, a newer full replacement can. Ensure URI close/reopen and lifecycle state are respected. +4. All pre-existing tests except the two known upstream regressions retain intended behavior including real executable and framing/parsing failures; add checks for invalid egress before a frame write. + +## 11. Verification commands and evidence +Build/test using dev cpp-gcc -c vbs build and vbs test with the project/build dir/profile explicit; the verified local seed path is build/tools/vbs-6c225-bin/bin/vbs. Run all suites directly if a runner aborts at upstream numeric failures. Run comparison CMake build and ctest --output-on-failure on build/bootstrap. Verify registered bodies and both process transcripts. Run clang-format on exactly the owned C++ paths and git diff --check. + +## 12. Constraints and stop conditions +Continue independent root work while worker headers settle. Avoid simultaneous editing with source workers. If exact classification requires unavailable upstream information, preserve the original failing cases and the dependency owner decision; do not add a decimal parser here. + +## 13. Authorization and decisions +Implementation of roadmap 02/03 is authorized. Keep primary VBS, current branch, VoidLibrary main and existing preflight ownership. No staging, commits, push or sibling changes. Root owns integration. + +## 14. Return format +Record implementation, exact commands, observed outputs and any remaining dependency problems in VERIFICATION.md and STATE.md. Fresh integrated adversarial review required before merge/release. diff --git a/docs/agent-workflow/tasks/T-SESSION-PASSIVE-007.md b/docs/agent-workflow/tasks/T-SESSION-PASSIVE-007.md new file mode 100644 index 0000000..6c32538 --- /dev/null +++ b/docs/agent-workflow/tasks/T-SESSION-PASSIVE-007.md @@ -0,0 +1,49 @@ +# Implement per-workspace provider selection and status + +Task ID: T-SESSION-PASSIVE-007 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Shared /home/faumaray/Projects/VoidLanguageServer, feat/implement-roadmap at ca04975, dirty files authorized. Primary native descriptor build.cpp, optional CMake verification, VoidLibrary main 7d7d23e. T-PLAN-006 verified VBS 6c225c2 selector/status/generations and actual compdb rows. Build/Model.hpp, Workspace/{Configuration,Trust}.hpp and Protocol/Json.hpp are implemented. Root owns build/test registration, CLI, session, docs and integration. No shared tree branch switches, Git mutations, sibling writes, child agents or independent user messages. + +## 2. Objective and deliverables +Implement the workspace session controller and focused race tests from the amended, independently cleared T-PROVIDER-SESSION-007. The root handles CLI, stdio dispatch, standalone compdb adapter and real process transcripts. + +## 3. Scope and non-goals +Controller plus tests only, no LSP lifecycle changes, compiler launches, scheduling workers, sibling reads/writes or build registration. The independent reviewer completed all four provider verdicts; this task splits out the already-reviewed controller. + +## 4. Files to inspect +Read docs/agent-workflow/tasks/T-PROVIDER-SESSION-007.md, src/Server.cpp, include/vls/Server.hpp, actual include/Void/LanguageServer/Build/{Providers,Model}.hpp, Workspace/{Trust,Configuration}.hpp, Documents/Uri.hpp, src/Workspace/Configuration.cpp, existing tests/workspace/WorkspaceTests.cpp. + +## 5. Write ownership and coordination +Write scope: include/vls/WorkspaceSession.hpp; src/WorkspaceSession.cpp; tests/workspace/ProviderSessionTests.cpp +Root releases these three paths exclusively to you. All other paths including src/main.cpp and both builds are root-/other-owned. + +## 6. Implementation or investigation approach +Implement bounded initialize workspaceFolders, then legacy rootUri only if absent, explicit null or empty folders supports document-only. Accept file URIs and stable existing roots, normalize safely. Track LSP add/remove and settings changes per workspace, support initializationOptions.voidLanguageServer and didChangeConfiguration params.settings.voidLanguageServer as passive default settings. Permit explicit scoped per-folder payload under a documented key (e.g. workspaces keyed by folder URI), retain workspace vs launcher provenance. Each folder has unique session/incarnation, config and trust generation. Only explicitly selected launcher root can use external exact locators or approved build root/producer cwd. Bind anchors once at grant ingress, never broaden after a path is redirected. Install TrustPolicy from merged configuration. Auto prefer real VBS selector even broken; only proven missing allows explicit or conventional compile_commands.json. Avoid all VBS managed aliases as automatic fallback (including generation-targeting symlinks); observe both selector absence and ordinary DB current before publication. No fallback for explicit broken provider. Native read via observe_vbs; compatibility via observe_compdb; true no-root supports normal docs. + +## 7. Interfaces and data contracts +NEW vls::WorkspaceLaunch carries optional root, build_root, producer_cwd and optional user_settings, cli_settings. NEW vls::WorkspaceSession(WorkspaceLaunch = {}), std::expected initialize(const Protocol::Json& params), update_folders(const Protocol::Json* params), configure(const Protocol::Json* params); std::expected provider_status(const Protocol::Json* params). Root supplies launch slots only from CLI. Status params {workspaceUri?,textDocument?:{uri}}; explicit root or unique matching root, error for ambiguous query. Return workspaceUri/incarnation/provider/requestedProvider/state, generation and nativeGeneration if present, profile/ticket, contextCount, bounded issues,warnings, selected and alternatives for a document with deterministic Build::SelectionState (selectedProfile preference). Distinguish historical last-good identity, degraded/missing/stale/disabled, document-only when no workspace. Protocol names camelCase; coordinate exact keys early for process tests. No fabricated AST/semantic status. + +## 8. Dependencies and integration +ProviderFile + row importer are concurrent tasks. Root is implementing observe_vbs and observe_compdb. Public APIs usable immediately; no placeholder implementations in shared source. Write focused tests exercising real providers once linked, or independent staged begin/observe/install paths for races. Root integrates three owned paths in the native and CMake targets. + +## 9. Edge cases security and performance +The root implemented the scoped reader in src/Build/ProviderFile.cpp; seven targeted tests pass. For a launcher-selected root, bind the external exact paths/build root once at launcher ingress, retain the bound scope across client configuration updates and root re-adds, and use reuse_provider_scope(bound,new_session) to reuse the original pinned directories for a fresh workspace incarnation. Keep this anchor binding separate from the merged per-folder limits and untrusted settings. A detached/replaced directory remains ineligible. In tests the controller may have an explicit observation callback/testing seam to prove late publications; use distinguishable real selectors/databases. Root owns CLI, provider tests and integration. The previous session writer hit HTTP 429 before creating any of your three files. +Issue monotonic sequence before EACH observation and validate latest issuance, immutable owner/incarnation, configuration, trust and all positive/negative lookup evidence before publishing success OR failure. Preserve last-good separately, invalidate on reconfigure/revoke/removal. Do not hold session map mutex across I/O. A late completion cannot restore retired state. Distinguish missing status/db/unsafe selector from genuinely absent selector. Bound roots, alternatives/status response and errors. Driver evidence absent stays passive; no wildcard grants from user configuration across folders. + +## 10. Acceptance criteria +Real ProviderSession tests for two independent roots, absent/empty/legacy roots, bad folders/config, change/removal/re-add, explicit broken native override, native-before-cdb, marker remains untouched and external grants bound to one launcher-selected root. Deterministically introduce selector after fallback probe, reorder successful+failed reads across config/trust/root reincarnation. Expose latest outcomes and stale historical IDs without promoting stale work. Preserve caller's known documents/cache state on malformed transactional updates. + +## 11. Verification commands and evidence +Use git status --short --branch, scoped graph coverage plus direct reads, dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only on the owned sources and tests, then link/run the actual Void::Testing suite in a private build subdirectory. Use dev cpp -c clang-format --dry-run --Werror on owned C++ paths. List the cases via --list --no-color. Root owns the two shared build trees. Root registers tests under vls_workspace_tests and integrates real executable behavior. Contact root early with constructor/wire signatures and result field names. + +## 12. Constraints and stop conditions +Stop before a new public product capability, additional security authority, incompatible shared API or repeated repair failure. Return actual tested versus pending integrations. Testing must never execute metadata. + +## 13. Authorization and decisions +The original session contract received independent Astra READY after amendments. D-022/D-025–D-030 apply. User requested GPT-6.2 family at Max; this is the general implementation portion of the cleared session design. + +## 14. Return format +T-SESSION-PASSIVE-007 DONE/PARTIAL/BLOCKED, exact paths, API/wire status fields, test evidence, residual gaps and root integration needs. diff --git a/docs/agent-workflow/tasks/T-SOURCE-CATALOG-009.md b/docs/agent-workflow/tasks/T-SOURCE-CATALOG-009.md new file mode 100644 index 0000000..fb55bd7 --- /dev/null +++ b/docs/agent-workflow/tasks/T-SOURCE-CATALOG-009.md @@ -0,0 +1,50 @@ +# Capture exact source and lookup observations under a compiler job's source roots + +Task ID: T-SOURCE-CATALOG-009 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared branch feat/implement-roadmap ca04975 with current integrated DocumentStore, Build model, and stock SARIF adapter. Actual controlled GCC job accepted the original Documents TU and diagnosed the edited missing name. Root also compiled that native row with stock cc1plus in a private Linux namespace at its original source names. T-PLAN-SEMANTICS-010 calls for FD-bound source capture. T-SOURCE-OVERLAYS-009 has a frozen API, implementation underway. + +## 2. Objective and deliverables +Implement the Linux source acquisition library for an immutable compiler job. Given an explicit caller-authorized root set, exact requested file bindings and lookup observations, return retained logical names, origin, ready overlay or opened disk content and positive/negative namespace evidence. Revalidate the entire observed set and document authority at dispatch/publication. This library supplies input data for the upcoming unmodified stock runner, without launching it. + +## 3. Scope and non-goals +Exact named inputs only in this slice. No directory crawls, automatic approval of paths from metadata, external process, sandbox implementation, compiler readiness or proof that a positive depfile describes every possible compiler lookup. A caller still supplies closed lookup scope or imposes/traces the actual worker's filesystem view. Do not copy a repository tree. + +## 4. Files to inspect +Read include/Void/LanguageServer/{Support/RegularFile,Documents/{DocumentStore,DocumentSnapshot,Uri},Build/{Model,Providers}}.hpp; src/Build/ProviderFile.cpp; src/Documents/{DocumentStore,Uri}.cpp; tests/providers/ProviderFileTests.cpp; current T-SOURCE-OVERLAYS-009 contract plus frozen header; T-SEMANTIC-LEASE-009; src/semantic/Diagnostics.cpp and tests/corpus/frontend/verify-stock-diagnostics.py. Reuse existing fd streaming and logical-vs-physical document identities. Inspect actual available Linux/Void::System APIs. + +## 5. Write ownership and coordination +Write scope: include/vls/semantic/SourceCatalog.hpp; src/semantic/SourceCatalog.cpp; tests/semantic/SourceCatalogTests.cpp +Private build/source-catalog-009 for tests only. DocumentStore and WorkspaceSession have different active owners; communicate missing interface through root. No other file edits, registration, Git, external actions or child agents. + +## 6. Implementation or investigation approach +Bind each caller-selected normalized absolute directory to an immutable handle and the actual directory route for the lifetime of a workspace incarnation and authority generation. Source roots can include the selected TU or an explicitly granted include root. A compilation database row alone grants neither external reads nor tool execution. Initial implementation may reject unsupported symlink/.. routes, but never silently normalize to a different source. Support normal in-root lexical paths and uncreated unsaved leaves. Check components and retain logical/file/namespace identities from the same opened objects. For disk, open bounded regular nonblocking descriptor, verify shape and stable metadata both sides of streaming using existing stream_regular_fd or equivalent; avoid reopening source bytes. Use DocumentStore's caller-bound overlay API before any disk content read. An unavailable/ambiguous editor binding vetoes disk. Positive overlays override bytes on disk including an empty overlay. Capture genuine missing candidates only on proven absence; retain named parent/authority evidence so later creation or redirection invalidates the observation. Distinguish requested required missing inputs from a recorded negative lookup. Revalidate path membership and object identity along with checked document census; consider races after opening and during multi-file capture. If evidence expires, old slice stays historical, with no accidental admission after observed invalidation. Prefer simple bounded conservative rules over a filesystem-wide watcher. + +## 7. Interfaces and data contracts +NEW namespace vls::semantic; exact names freeze early. Suggested SourceGrant/SourceRoot carries Build::WorkspaceIdentity plus caller config/trust epoch, reusable pins; SourceRequest names absolute logical path and whether absence is allowed; capture_sources(authorized roots, DocumentStore, span, limits) -> expected; validate_sources(capture, current scope, store) rechecks exact evidence. Expose immutable entries (logical physical names, presence and snapshot) plus census/authority/membership identity usable to populate AnalysisInputs. Preserve request order or return a documented deterministic alias mapping. Negative optional lookups can become ready with an unsaved new header. Multiple names must retain all logical receipts. For hard-linked files define safe handling of authoritative overlays (detect and reject ambiguous bindings, or return typed unsupported hardlinks). A request must never see unrelated file bytes from a root/epoch mismatch. No unsupported positive statement that this is a complete universe. + +## 8. Dependencies and integration +Before reading payload bytes, match the job's expected workspace incarnation, configuration, trust generation and installed grant-set identity against its actual current grants. Retained grants for another root or a previous settings epoch cannot authorize acquisition even if the include directory is shared. A revocation overlapping acquisition must fence publication. If a caller built the request list from an overlay inventory, accept and validate that exact inventory throughout capture; obtaining a newer internal census cannot justify names computed from an older one. Exercise the empty-inventory → unsaved header race and verify wrong-grant requests read no source bytes. Exact path receipts alone cannot populate the all-roots AnalysisInputs.lookup_epoch. +Frozen Documents API: file_overlay_inventory(max_entries), observe_bound_source(inventory,file_uri,physical_path), materialize_bound_disk(observation,string), validate_bound_sources(inventory,span) with per-store epoch/readiness checks. Wait for header before direct compilation; independent source acquisition code and tests may start after preflight. Root owns CLI/scheduling, private view/real worker, executable fixtures and build registration. New model/lease/workspace and source acquisition identities are passed by the caller; these separate APIs neither authorize execution nor choose a production compiler. + +## 9. Edge cases security and performance +Apply bounded source count, aggregate source/retained name bytes, path/component depth, per-file bytes and fd count. Avoid holding document locks across IO; fail cleanly on read errors, stale/replaced parent or leaf, nonregular inputs, and unsupported route or incomplete evidence. Do not follow an unreviewed route from scope. Avoid a check-then-open path gap and avoid treating permission denied, symlinks or ENOTDIR as absence. Existing exact compiler or module output doesn't make input read-only on disk. + +## 10. Acceptance criteria +Check cross-entry namespace consistency independent of request order. A requested negative file at generated/ and a positive unsaved generated/config.hpp cannot coexist if the former means genuine namespace absence. Two requested positive regular files at an ancestor and its descendant cannot both be materialized. Reject with a typed inconsistency or require a proven existing directory where appropriate. Include a disk leaf with two hard links where only one spelling is requested and its other spelling has an empty overlay. No ambient disk bytes may override the editor's authority. +Cases: saved disk vs unsaved edit/empty overlay, missing file overlay and truly negative lookup then create, refused/desynced/ambiguous overlay, disk leaf identical-byte replacement, rename/replacement of a bound root or parent, nested and overlapping admitted roots, same physical multiple names including hardlinks, file/lookup route escaping scope (fail without reading external bytes), wrong scope/census/revocation, quota and FIFO. Include deterministic capture-vs-open/edit race and retained old readers. A caller observing only one named lookup cannot obtain a universal namespace-completeness claim. Test ordinary regular paths and non-ASCII file names under the original logical directory. + +## 11. Verification commands and evidence +Run dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only src/semantic/SourceCatalog.cpp tests/semantic/SourceCatalogTests.cpp after frozen dependency. Private Void::Testing runner allowed. Root wires VBS/CMake and repeats relevant real corpus when data API is stable. State actual case names/counts, exits and conservative limitations. + +## 12. Constraints and stop conditions +Stop for necessary API changes outside owned files or unexpected permissions requirement. No network, install, executable derivation or filesystem updates outside private benign temp fixtures. Do not flatten missing/unsupported/incomplete into a usable snapshot. + +## 13. Authorization and decisions +User authorized roadmap 03/05/09/13, VBS primary, separate branch, GPT-6.2 Max. Execution/ABI/license remain distinct D-028/030 gates. This is a C++ data/library slice for the real pipeline. + +## 14. Return format +T-SOURCE-CATALOG-009 DONE/PARTIAL, exact types and handling of disk, editor overlay, negative lookup and revalidation, tests with actual exits, limits, true authorizations still needed and released write paths. Announce frozen interface early. diff --git a/docs/agent-workflow/tasks/T-SOURCE-OVERLAYS-009.md b/docs/agent-workflow/tasks/T-SOURCE-OVERLAYS-009.md new file mode 100644 index 0000000..80d7219 --- /dev/null +++ b/docs/agent-workflow/tasks/T-SOURCE-OVERLAYS-009.md @@ -0,0 +1,50 @@ +# Bind editor overlays and directory-authorized disk inputs to one diagnostic view + +Task ID: T-SOURCE-OVERLAYS-009 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared feat/implement-roadmap at ca04975 plus unstaged implementation. T-PLAN-SEMANTICS-010 approved a stock diagnostic path for real Void contexts. The native capture fixture verifies GCC SARIF output and overload edits. DocumentStore::resolve_content(path) checks overlays and detects mid-read replacement, but opens by path on its own. list_overlays only lists readable texts. A future source-catalog owner has directory-bound file handles and needs to use the actual editor authority without opening the ambient path again. + +## 2. Objective and deliverables +Implement the document-side capture interface for a private compiler input view. A caller with a bound logical/physical source identity can query overlay/blocked/absent state, materialize already-authorized disk bytes into a budgeted immutable DocumentSnapshot, and enumerate file-overlay membership (including unsaved new headers and refused/desynchronized opens). Verify selected input authority is still current. Keep current public caller behavior. + +## 3. Scope and non-goals +Document store support only. No compiler, IPC, file grant checker, filesystem staging, directory enumeration or process. The caller retains actual FD/path/lookup evidence and revalidates it separately. The snapshots must work with current AnalysisInputs, same_input_as and UTF encodings. + +## 4. Files to inspect +Read include/Void/LanguageServer/Documents/{DocumentStore,DocumentSnapshot,Uri,Position}.hpp; src/Documents/{DocumentStore,DocumentSnapshot,Uri,Position}.cpp; include/Void/LanguageServer/Support/RegularFile.hpp; tests/documents/{DocumentTests,LongLineTests}.cpp; docs/agent-workflow/tasks/T-DOCS-003.md; tests/semantic/DiagnosticTests.cpp. Confirm file-vs-nonfile/unknown-open, byte budget, ABA and discarded-open semantics before implementation. + +## 5. Write ownership and coordination +Write scope: include/Void/LanguageServer/Documents/DocumentStore.hpp; src/Documents/DocumentStore.cpp; tests/documents/BoundInputTests.cpp +No changes to existing tests or Uri, compiler/library/provider implementations, sibling repositories, shared build manifests or Git. Root owns actual disk/catalog implementation and build/test wiring; semantic lease owns only WorkspaceSession. Private build/bound-inputs-009 okay. No further delegation or user communication. + +## 6. Implementation or investigation approach +Build on overlay_for_path, existing retained snapshot accounting, negotiated encoding, original client key and actual bound physical path. Freeze exact API early. Support an atomic bounded inventory of FILE overlay bindings with identity, ready snapshot or typed blocker; include refused/known without text. Expose an explicit failure for unbound/unrepresentable file opens/overflow rather than turning them into absence. For an already-bound disk candidate, offer an opaque capture/observation scoped to this store, the exact client/physical binding and its authority generation. An API accepting caller-owned bounded bytes may create a disk snapshot only after an eligible absent-overlay observation. Standalone source input should have zero ambient IO: do not canonicalize/reopen the already-bound file or recompute identity_from_path. Avoid duplicate copies of stored texts; reuse make_snapshot with existing budget and validate UTF8/size. A caller checks overlay state before reading disk; reject a race or return the newly authorized overlay by a documented typed outcome. Source owner separately checks FD/name and whole view before dispatch/publication. + +## 7. Interfaces and data contracts +NEW public API with named types for the file overlay inventory and one bound source observation. Inventory retains lexical URI and physical path so callers can filter the exact approved source roots, detect alias ambiguity, include newly opened unpublished headers, and distinguish an absent binding from a blocked one. DocumentStore may use an opaque capture stamp carrying store identity, negotiated encoding/overlay epoch and selected overlay revision/absence. A validator must reject observations from another store even if allocator addresses are reused. Explicit overlay edit/close/reopen, new alias, desynchronization without a higher version and resource-refused opens invalidate as appropriate. Reads in truly independent documents should remain usable across unrelated text edits; conservative existing membership epoch on open/close/encoding is acceptable. Do not confuse this with proving a filesystem lookup closure or compiler run. + +## 8. Dependencies and integration +The captured overlay inventory has its own opaque, store-bound membership/encoding generation captured under the same lock, including when it is empty. All selected observations must belong to that inventory generation and its membership must still be current at validation. Use an observation's current generation, distinct from a retained overlay snapshot's creation epoch. Edits/desync need checks on the selected entries even if membership is unchanged. Test empty census → open unsaved optional.hpp → observe unchanged TU, and obtaining a fresh valid observation of an older overlay after an unrelated file opens. Unrelated text-only edits may leave an existing observation current. +Preflight required and existing T-PLAN-SEMANTICS-010 names the need. Independent T-SEMANTIC-LEASE-009 has disjoint ownership. Root will consume the public API in a scoped stock source catalog. The existing program still uses resolve_content and public lifecycle methods. Their longstanding unit and process cases must continue passing. The stock JSON regressions are separate. + +## 9. Edge cases security and performance +Avoid running user callbacks under mutex, unbounded retained paths, repeated text copies or bypass of retained-byte limits via caller-constructed snapshots. Charge disk acquisition promptly and never produce version for a disk snapshot. Bulk inventory must remain bounded with 4096 admitted/4096 blocked configured defaults; return typed saturation for caller-provided lower limit. Avoid using URI string normalization to erase alias/parent traversal. No leaking text through inventory for blocked documents. Fail conservatively for unsupported identity/cross-store stamps; tolerate empty text as a valid overlay/disk input. + +## 10. Acceptance criteria +File-only coverage distinguishes a refused known virtual URI from a refused real-file URI when even the marker budget is exhausted. With one admitted file and zero spare marker slots, refusing an untitled document must leave the file census and capture usable. Refusing another file must block file authority until the store can establish complete coverage again. Fail conservatively when the URI cannot be classified. Preserve virtual document lifecycle behavior using the appropriate authority state. +Cases cover absent bound regular source, new unsaved overlay, refused and desynced overlay even at quota, visible recovery, two aliases of same physical file, retargeted lexical key, trusted caller disk bytes differing from ambient bytes (no ambient open), cache retention after store destruction, mismatched store, UTF8 and byte/line budgets. Deterministically interleave absent capture → open/change/close → supply old bytes, as well as edit/desync/reopen of a retained overlay. Check a changed unrelated overlay text doesn't invalidate an otherwise unchanged selection, with a distinct membership-change control. Validate library callers still see previous public behavior. + +## 11. Verification commands and evidence +Run dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/voidlibrary/current/include -fsyntax-only src/Documents/DocumentStore.cpp tests/documents/BoundInputTests.cpp, clang-format --dry-run on exact owned paths, private Void::Testing runner or parent-integrated target. Root adds test file to vls_document_tests (VBS and CMake). Report actual listed case names and counts. + +## 12. Constraints and stop conditions +Stop for shared-file ownership conflicts or need to change source trust policy. Capture bytes only from the passed bounded buffer. No auto-discovery, private compiler changes, fake scope completeness or unguarded edits. A compiler or source.catalog grant is outside this document-only layer. + +## 13. Authorization and decisions +Full roadmap D-022, Linux first, native VBS D-025, 6.2 family Max D-027, stock compiler evaluation D-028. Reversible local changes only, no Git staging or external sends. + +## 14. Return format +T-SOURCE-OVERLAYS-009 DONE/PARTIAL with frozen types/methods, invariants, actual verification outcomes, limits, dependency on caller's external input/lookup evidence and released source paths. diff --git a/docs/agent-workflow/tasks/T-STOCK-OCCURRENCES-014.md b/docs/agent-workflow/tasks/T-STOCK-OCCURRENCES-014.md new file mode 100644 index 0000000..3a2c560 --- /dev/null +++ b/docs/agent-workflow/tasks/T-STOCK-OCCURRENCES-014.md @@ -0,0 +1,50 @@ +# Produce compiler-owned call and definition facts with stock GCC 16.2 +Task ID: T-STOCK-OCCURRENCES-014 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Shared workspace /home/faumaray/Projects/VoidLanguageServer on feat/implement-roadmap, ca04975 plus uncommitted changes. D-028/030 approve local GCC evaluation. The planner T-PLAN-STOCK-NAVIGATION-014 built a separate observer against the unmodified installed GCC 16.2.0 and compiled the real DocumentSnapshot.cpp under a sealed Linux view. The saved TU selected Void::Hash::fnv1a64 at Hash.hpp:59; changing its argument to a byte span selects line 65, with canonical long unsigned int. Broken/recovery exits 1/0. Both calls have the same physical spelling; terminal information in CALL_EXPR is not a standalone token location. + +## 2. Objective and deliverables +Implement a local development observer that a verified regular GCC 16.2 cc1plus can load to publish source-bound facts for resolved direct calls in the selected translation unit and actual function definitions in the captured file set. Build/installing the user's compiler is outside scope. Deliver an opt-in development build tool and actual closed-fixture tests. Root owns StockCompiler, profile, server, semantic result binding and LSP; work entirely in the owned three paths. + +## 3. Scope and non-goals +C++ direct free/namespace function calls, ASCII identifiers in a conservative source grammar; overloads, declared-only cases, and an explicit incomplete-coverage result. Positive physically verified use and target identity only. Support the actual overload/type edit in Void. Later plugins/features may add class members, completion, templates and reflection. Never hardcode Void symbol names, fixture values or paths. Do not choose a project license or distribute a shared object. + +## 4. Files to inspect +Read build/plan-stock-navigation-014/{probe.py,observe.cc,real.py} and private sealed evidence as available, root's tests/corpus/frontend/gcc-queries.cpp and gcc-live.cpp, src/Documents/DocumentSnapshot.cpp, prepared Void/Core/Hash.hpp, compiler-patches/gcc-16.2.0/{0002-ide-occurrences,0003-physical-utf8-origin}.patch, tools/prepare-gcc-profile, src/semantic/StockCompiler.cpp. Verify plugin header callbacks from stock GCC dev shell. The checked-in app does not yet consume this wire. + +## 5. Write ownership and coordination +Write scope: experiments/frontend/gcc-observer/Observer.cpp, tools/prepare-gcc-observer, tests/corpus/frontend/verify-stock-observer.py +Private artifacts in build/stock-observer-014 only. No compiler source edits, shared worker, profile, VBS/CMake, fixtures already owned, LSP dispatch, docs or Git. No subagents or user contact. Coordinate final wire names and proofs with root. Root owns host decoder and launcher assembly. + +## 6. Implementation or investigation approach +Use the actual stock GCC plugin ABI with version checks. Observe function bodies before genericization, selected direct callee identity, canonical and spelled return type; join definitions only to an observed function body in the same invocation. Keep location, line-map and GCC UID inside this process until projecting copied facts. Restrict parsing to files named in the sealed job manifest, read exact immutable stage bytes and prove both physical endpoints. Use CALL_EXPR start/caret/finish, original source and restricted ordinary qualified-id grammar to isolate a unique terminal identifier before '('. Withhold on remap, hidden macro expansion, overlapping/ambiguous facts, missing definition, malformed encoding/columns or quota. A defined-only/overloaded-ambiguous token never supplies a unique definition. Filter or suppress correctly for template specializations/instantiations before committing the unique occurrence. Ignore #line, macro-generated locations and BOM-shifted coordinates unless independently proven. Runtime must not override handlers needed by GCC itself. + +## 7. Interfaces and data contracts +NEW supervised observer mode uses three fixed, program-selected resources in the private worker. Bind verified ELF at /vls-observer/occurrences.so; arguments -fplugin=/vls-observer/occurrences.so with no compiler options forwarded from build metadata. A reads-only config file /vls-observer/inputs contains a schema line VLS-OCCURRENCES-1, nonce on second line (32 lowercase hex), absolute primary file path on third line, and remaining absolute source paths one per line. Require only admitted absolute paths, nonempty lines, max 1024 inputs, length <=4095, no NUL or line breaks. For independent harnesses allow *test runner selected* absolute input/output paths in explicitly named environment VLS_OBSERVER_INPUTS, VLS_OBSERVER_OUTPUT exclusively on the private plugin test leg; normal server supplies only constants inside its sandbox. Use one fresh private report at /vls-observer/report. Default report format UTF-8 strict JSON envelope {schema:1,nonce,complete:true,partial:boolean,occurrences:[{name,type,canonicalType,use:{path,line,startByte,endByte},definition:{path,line,startByte,endByte}}]}. All fields owned, one-based byte/line coordinates, half-open ranges in original captured UTF-8 bytes. Partial means supported individual facts only; complete means normal report finished, not project-wide semantic completeness. Conflicting target/type at any single physical use is unavailable independent of iteration order. Global invalidity (compiler error, remap, quota) yields zero facts and explicit reason/incomplete status. No parser for user C++ types in the host. Use strict escaping even for controls in render strings, or withhold unsupported output. Root must independently verify nonce/fields/path/spelling/ranges/encoding and revalidate revision and scope at delivery. Confirm wire and build command to root early. + +## 8. Dependencies and integration +Refinement from the completed planner proof. A positively identified unique direct call can carry a compiler-proven type even when no physical defining token is available. Encode `definition: null` in this case. Conflicting invocation-local semantic identities at one use suppress the entire occurrence. Copy the bounded GCC signature into a `signature` string when available for hover, alongside `type` and `canonicalType`. The host will require a proven physical definition before serving a location. +Dispatch depends on independent preflight of the current contract. +The producer preflight cleared the observation logic and found a mutable repository RUNPATH in the private probe ELF. Build the checked artifact with a scrubbed compiler/linker environment and explicit, verified ABI headers and runtime search directories. Inspect its actual dynamic section before publishing. Reject relative, workspace, empty or unapproved loader search entries, unexpected DT_NEEDED or loader extensions, and any dependency outside the selected immutable GCC runtime closure. Verify required SONAME resolution against approved immutable libraries or already loaded frontend libraries with proven identities. Include the admission inputs in the build result for the server's independent check. Reproduce rejection of the planner's binary with its project RUNPATH, and demonstrate the prepared observer works in the actual sealed runtime. A digest of the observer alone does not establish its dependencies. +Stock dev driver, its installed GCC plugin headers (g++ -print-file-name=plugin), same immutable GMP dev include from the selected compiler build environment, export ABI marker required for local experiments. Use a fixed source and absolute selected compiler for building this development observer, no workspace-provided compiler argv/plugins. tools/prepare-gcc-observer --output ABSOLUTE_SO should invoke stock build, validate version, publish atomically, print SHA-256 and matched ABI. Root integrates only an explicit launcher-selected artifact digest into GCC profile. Compile project with its ordinary toolchain and keep diagnostics working with no plugin. The local roadmap expressly defers distribution or project license. + +## 9. Edge cases security and performance +Bound recursive/tree walk, macros, strings, observations, matching candidates, bytes read, report size and file descriptors. Avoid excessive traversal for stdlib or unrelated bodies. Avoid repeated per-call full source and macro-map scans. No arbitrary output target in production; private test paths never enter project server options. Report resource exhaustion, unknown call expression, overloaded macros/self-name macro after undef, same-token dependent instantiations, qualifier with same terminal name, declaration merging and malformed units. Correct header definitions and typed overloads within the selected immutable file set. Avoid stdout/stderr pollution on a successful observed compile and persistent GCC tree pointers across invocations. + +## 10. Acceptance criteria +1. Fresh stock GCC and matching headers build/load the observer. 2. Normal two same-line overloads select distinct witnessed definitions and int/double after edit; include genuine Void data or the planner's original and byte-span checked fixture. 3. Header shifts and recovery are detected; macro/#line/same-name qualifier, declared-only and conflicting template instantiations never create an incorrect occurrence. 4. Verify raw spans against captured bytes, UTF-8 BOM, names containing spaces and both release/malformed/quota behavior. 5. Root can consume a report from an explicitly configured, unmodified compiler using the fixed runtime paths. + +## 11. Verification commands and evidence +Use dev cpp-gcc -c g++ --version, dev cpp-gcc -c tools/prepare-gcc-observer --output "$PWD/build/stock-observer-014/occurrences.so", then dev cpp-gcc -c python3 -B tests/corpus/frontend/verify-stock-observer.py --observer "$PWD/build/stock-observer-014/occurrences.so". Provide the observed command if actual dev-shell dependency discovery needs adaptation. Verify syntax and clang-format only owned files. Never invoke a full GCC rebuild or switch a shared selector. Derive other probes from existing checked stock corpus. + +## 12. Constraints and stop conditions +Stop on unresolvable ABI/provenance or product licensing/distribution decision, return evidence to root. Do not add a compiler dependency for the default build, a process launcher under LSP project authority or fake analysis to fill a gap. An unprovable individual case returns unsupported within scope. Do not modify compiler, user's shell/environment, sibling repositories or any existing relevant files not explicitly owned. + +## 13. Authorization and decisions +D-022 full implementation, D-025 native primary, D-027/029 GPT-6.2 Astra at Max, D-028/030 opt-in compiler experiments on this branch. The local header/ABI use and packaging of the release are separate; do not assert a release license. + +## 14. Return format +T-STOCK-OCCURRENCES-014 DONE/PARTIAL, paths, exact ABI and proof, wire/build details, tests and outcomes, limitations and release of ownership. Return earliest usable compiled producer and scope of evidence; no subagents. diff --git a/docs/agent-workflow/tasks/T-TRUST-004.md b/docs/agent-workflow/tasks/T-TRUST-004.md new file mode 100644 index 0000000..8e3b760 --- /dev/null +++ b/docs/agent-workflow/tasks/T-TRUST-004.md @@ -0,0 +1,67 @@ +# Implement passive workspace configuration and tool identity checks + +Task ID: T-TRUST-004 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Repository /home/faumaray/Projects/VoidLanguageServer on feat/implement-roadmap at ca04975. Existing untracked Workspace/Configuration and Trust.hpp are authorized continuation with no other writer. R-007, R-008 and R-021 require separating metadata from execution authority. GCC 16.2 and VoidLibrary main 7d7d23e are available locally. + +## 2. Objective and deliverables +Complete a tested passive workspace foundation. Resolve layered settings, bind user-selected executable identities and validate normalized command data. Supply tests for revocation, replacing tool contents and untrusted settings. Future process launch, provider loading and semantic workers will consume the boundary. + +## 3. Scope and non-goals +Workspace configuration, trust, static classification and focused tests only. This slice never executes a compiler/VBS/tool/plugin/wrapper. Process sandboxing, launching through a mutable pathname, OS process trees, actual build permissions, server schema/wire integration and response-file expansion belong to consumers. Keep unresolved driver behavior explicit. + +## 4. Files to inspect +Inspect include/Void/LanguageServer/Workspace/{Configuration,Trust}.hpp and src/Workspace/Configuration.cpp, relevant Protocol/Json.hpp accessors, docs/roadmap/{04-workspace-configuration-trust,05-build-contexts,07-compilation-database,09-semantic-workers}.md and ARCHITECTURE.md. Void::Crypto::Hasher, sha256 and file primitives are in the actual upstream public headers under build/bootstrap/_deps/voidlibrary-src/include/Void. Review T-PLAN-002 and the fresh preflight supplied by root. + +## 5. Write ownership and coordination +Write scope: include/Void/LanguageServer/Workspace; src/Workspace; tests/workspace +New files include src/Workspace/Trust.cpp and tests/workspace/WorkspaceTests.cpp. Shared checkout. Root owns build wiring, actual stdio/session and docs. No edits to Protocol, Documents or siblings. No branch changes or Git writes. + +## 6. Implementation or investigation approach +Inspect before editing. Reject or diagnose invalid types and limits. Resolve relative settings against their owning layer/base and preserve distinct roots. Accept security grants only from validated user/runtime or CLI sources; plugin execution stays unsupported. Validate root containment by path components, distinguish explicit invocation from persistent trust and fail closed on missing/ambiguous identity. Use a strong digest of the same opened regular executable and revalidate on identity changes. Keep the original approved spelling if a symlink retarget must revoke approval. Revocation and generation checks must avoid races and callback deadlock. Use the planner/preflight decisions for exact operation types and model identity. Classify canonicalized argument vectors passively after bounded expansion by a future provider. Apply a conservative grammar for supported compiler inputs; reject unresolved driver/plugin/wrapper/indirect options as unsupported. Wrapper recognition only strips a data prefix. Emit actionable typed reasons. + +## 7. Interfaces and data contracts +Existing WorkspaceSettings, PartialWorkspaceSettings, MergedConfiguration, ToolIdentity, TrustPolicy and CommandSecurityReport are the starting interfaces. Freeze the exact API with root if planner changes a permission or signature. A returned identity report has no power to launch a process. A launch implementation must later bind the approved executable and a current trust generation at actual dispatch; communicate that invariant. Different roots and levels remain distinct. Use VoidLibrary for JSON/digest, std::expected for explicit failures. + +## 8. Dependencies and integration +Root integrates the native/CMake targets, then uses the policy in the provider and work queue. Other workers own documents and the protocol wrapper. Your tests should use native VOID_TEST names. Report the exact modules and build defines required (Void::Crypto hashing works without OpenSSL). + +## 9. Edge cases security and performance +Bound file reads and synchronous work. Handle missing/nonregular files, symlink retargeting, executable-bit changes, tool-content changes with identical length/mtime, untrusted roots and denied repetition. Use benign marker files for a proof of passive behavior. Do not create exploits, execute project-provided code, or inspect workspace secrets. Repository configuration cannot raise resource ceilings or mint execution tokens. + +## 10. Acceptance criteria +1. Layer precedence and authority failures are covered, including malformed fields and two roots with different policies. +2. An approved executable's changed bytes/permission/symlink invalidate the decision. Missing SHA-256 or ambiguous paths fail closed. +3. Revocation changes generation before callbacks and stale work loses eligibility. Classifier distinguishes trusted command data, inert recognized wrapper spellings and refused execution-bearing options. +4. Nonzero C++ tests execute through Void::Testing and leave marker files untouched. State unimplemented launch-time guarantees honestly. + +## 11. Verification commands and evidence +From repository root: dev cpp-gcc -c g++ -std=c++26 -freflection -Iinclude -Ibuild/bootstrap/_deps/voidlibrary-src/include -fsyntax-only . Link a focused executable under build/workspace-check or use root's integrated target when ready. Verified native seed at build/tools/vbs-6c225-bin/bin/vbs, test runner/archives under build/vbs-framework-probe. Crypto library from committed-seed CMake exists at build/tools/vbs-6c225-bin/_deps/voidlibrary-build/libVoid_Crypto.a for a focused comparison only. Record actual compiler flags, executions and counts. Format owned C++ with dev cpp -c clang-format. + +## 12. Constraints and stop conditions +Stop before any launch API starts running code or if response-file expansion/model changes cross worker boundaries. Escalate technical disagreements to root. After two failed repairs of the same issue return errors, diff and diagnosis. Never bypass review or permissions. + +## 13. Authorization and decisions +D-022, D-024 through D-027. The user authorizes the project feature on this branch and requires GPT-6.2 at Max. This difficult authority boundary is the Astra implementation assignment. No authorization to modify siblings, global settings or remote services. + +## 14. Return format +Return T-TRUST-004 DONE/PARTIAL/BLOCKED, exact files and signatures, tests/commands and outcomes, proposed consumer invariants, outstanding questions, and limitations against R-007/021. No children or independent user messages. + +T-PLAN-002 clarification: model distinct operation kinds for metadata refresh, +compiler use and a single explicitly requested project build action. Track the +approved executable path as spelled, the canonical referent, SHA-256 and a trust +generation. Root will read a user configuration only when the launcher explicitly +selects it. LSP initialization/configuration input has workspace provenance. +Use explicit configuration base paths and a hard ceiling for workspace-provided +resource limits. Missing per-operation authority must remain a typed denial. + +Preflight correction: scope each tool pin by workspace AND operation. No global +map of approved binaries can be combined with a different root's grants. +An explicit build approval is one-use and tied to the complete invocation +(root, selected tool, ordered arguments, working directory and relevant input +or generation identities). Do not let a metadata grant authorize a compiler. +Derive config origin at the reader boundary, retain it in the parsed settings +and prevent relabeling the same untrusted data as launcher input in the merge. diff --git a/docs/roadmap/01-bootstrap-dependencies.md b/docs/roadmap/01-bootstrap-dependencies.md index a5a34d3..943a202 100644 --- a/docs/roadmap/01-bootstrap-dependencies.md +++ b/docs/roadmap/01-bootstrap-dependencies.md @@ -1,6 +1,6 @@ # 01 — Bootstrap, dependency provenance and CLI -Status: PARTIAL (T-001); builds verified, final JSON acceptance blocked upstream +Status: IMPLEMENTED_TESTED; updated dependency integration awaiting independent review Requirements: R-001,R-003,R-005,R-022,R-026 Dependencies: None for repository/CLI; upstream VoidLibrary decimal revision gates final JSON acceptance. @@ -10,7 +10,7 @@ Future assignments must verify the then-current baseline and exact disjoint path these proposed scopes do not authorize work in another repository. ## Contracts and data flow -Build with GCC16+, C++26 and -freflection; CMake4+/Ninja. VLS_VOID_SOURCE_DIR is an explicit development override, never an implicit sibling lookup. Follow upstream main per user decision D-021 and record the tested commit and override provenance. CLI modes are default/--stdio, standalone --help/-h and --version/-V, with invalid/mixed options returning2. +Build with GCC 16+, C++26 and -freflection. D-025 makes VoidBuildSystem the primary build. CMake 4+/Ninja provides the previous bootstrap for comparison. VLS_VOID_SOURCE_DIR is an explicit development override. Follow upstream main per D-021 and record the tested commit and override provenance. CLI modes are default/--stdio, standalone --help/-h and --version/-V, with invalid/mixed options returning 2. ## Implementation sequence 1. Select only the verified Void module closure: Configuration/Data/Unicode, with System/Testing for tests. Disable dependency tests/benchmarks and keep output in the VLS binary tree; static linkage simplifies the initial executable. diff --git a/docs/roadmap/02-lsp-protocol-lifecycle.md b/docs/roadmap/02-lsp-protocol-lifecycle.md index a64ed95..957fedb 100644 --- a/docs/roadmap/02-lsp-protocol-lifecycle.md +++ b/docs/roadmap/02-lsp-protocol-lifecycle.md @@ -1,6 +1,6 @@ # 02 — LSP framing, JSON envelope and lifecycle -Status: PARTIAL (T-001); implemented shell, final JSON acceptance blocked upstream +Status: Lifecycle, checked serialization and synchronization are tested. The exact-number JSON gate passes on VoidLibrary main `9cb86f8f` after the StrictJson fix. Requirements: R-002,R-003,R-004,R-005 Dependencies: 01, including the verified upstream JSON prerequisite. @@ -24,7 +24,7 @@ Keep diagnostics on stderr, even after malformed input. Avoid responses to notif ## Acceptance scenarios 1. Feed one byte at a time, split CRLF/body/UTF-8 sequences, concatenate frames and assert complete exact messages with no extra stdout. 2. Test lifecycle ordering, repeated initialize, pre-init/post-shutdown requests, unknown notifications, both exit statuses and premature EOF. -3. Exercise valid decimal/exponent options, integral-valued/fractional/out-of-range IDs, unmatched responses, escaped IDs/astral characters, raw controls, lone surrogates, invalid UTF-8, depth limits and length overflow; enforce subprocess deadlines. Review the actual upstream numeric representation before accepting its integration; current StrictJson cannot exercise decimal ID handling. +3. Exercise valid decimal/exponent options, integral-valued/fractional/out-of-range IDs, unmatched responses, escaped IDs/astral characters, raw controls, lone surrogates, invalid UTF-8, depth limits and length overflow; enforce subprocess deadlines. Current upstream uses double for decimal syntax and now exercises the numeric visitor; independent review must assess this actual representation before integration acceptance. ## Verification and integration Run the documented configure/build/CTest commands from the repository README. Inspect ctest -N and test output for nonzero registration and real failures. Upstream main and local override use separate build trees. diff --git a/docs/roadmap/03-documents-positions.md b/docs/roadmap/03-documents-positions.md index d4232e1..fc5c769 100644 --- a/docs/roadmap/03-documents-positions.md +++ b/docs/roadmap/03-documents-positions.md @@ -1,6 +1,6 @@ # 03 — Versioned documents, positions and overlays -Status: PLANNED; no implementation claim +Status: Implemented and tested through stdio and the 17-case document suite. Integrated review and performance evidence are tracked separately. Requirements: R-006,R-011 Dependencies: 02; shared revision identity with05 and09 before semantic integration. diff --git a/docs/roadmap/04-workspace-configuration-trust.md b/docs/roadmap/04-workspace-configuration-trust.md index 3e843ba..d9f4fbc 100644 --- a/docs/roadmap/04-workspace-configuration-trust.md +++ b/docs/roadmap/04-workspace-configuration-trust.md @@ -1,6 +1,6 @@ # 04 — Workspace configuration and execution authority -Status: PLANNED; no implementation claim +Status: Passive settings and tool identity policy are implemented and tested. Launcher, provider and job integration are in progress. Requirements: R-007,R-008,R-021 Dependencies: 02; feeds05,06,07,09 and debugger launch. diff --git a/docs/roadmap/05-build-contexts.md b/docs/roadmap/05-build-contexts.md index a9605a9..a7a2b74 100644 --- a/docs/roadmap/05-build-contexts.md +++ b/docs/roadmap/05-build-contexts.md @@ -1,6 +1,6 @@ # 05 — Shared build contexts and profile/target selection -Status: PLANNED; no implementation claim +Status: The model's 18 cases and the workspace's 17 compiler-context lease cases pass in VBS and CMake. Native and compilation database leases select and revalidate the real Void translation unit used in the stock diagnostics corpus. Requirements: R-008,R-009,R-010,R-015 Dependencies: 03,04; freeze model before parallel06/07 implementation. diff --git a/docs/roadmap/06-native-vbs-tooling.md b/docs/roadmap/06-native-vbs-tooling.md index c572ca6..dcb3679 100644 --- a/docs/roadmap/06-native-vbs-tooling.md +++ b/docs/roadmap/06-native-vbs-tooling.md @@ -1,6 +1,6 @@ # 06 — Native VBS tooling export and consumer -Status: PLANNED; no implementation claim +Status: The passive VBS v1 reader and eight generation tests pass. It follows the selector, profile status and selected immutable compilation database. A richer producer export and its target, dependency, environment and module details remain upstream dependencies. Requirements: R-008,R-012,R-021,R-023 Dependencies: 04,05; live acceptance additionally requires separately owned VBS graph/toolchain/editor/module producer work. diff --git a/docs/roadmap/07-compilation-database.md b/docs/roadmap/07-compilation-database.md index 083dde2..2e1be8e 100644 --- a/docs/roadmap/07-compilation-database.md +++ b/docs/roadmap/07-compilation-database.md @@ -1,6 +1,6 @@ # 07 — Compilation-database compatibility provider -Status: PLANNED; no implementation claim +Status: The importer and compatibility provider pass their focused tests. Actual native and CMake command databases retain their alternatives, original command forms and repeated flags. The LSP session integration is being verified. Requirements: R-007,R-009,R-010 Dependencies: 04,05; may implement in parallel with06 after shared model freeze. diff --git a/docs/roadmap/08-frontend-feasibility.md b/docs/roadmap/08-frontend-feasibility.md index c0f7aca..ea28fd3 100644 --- a/docs/roadmap/08-frontend-feasibility.md +++ b/docs/roadmap/08-frontend-feasibility.md @@ -1,6 +1,6 @@ # 08 — Semantic frontend feasibility, toolchain and license gate -Status: PLANNED; no implementation claim +Status: The pinned Clang frontend fails the required GCC/libstdc++ fidelity gate. The GCC 16.2 reference corpus passed. Per D-028, GCC's suitability as an IDE and debugger backend is under evaluation. Requirements: R-010,R-012,R-013,R-016,R-026 Dependencies: Corpus definition from24 and actual build contexts from05/07 or equivalent captured fixtures; initial shell is independent. @@ -19,7 +19,7 @@ Candidate Clang/P2996 revision562409c7942690d59ea470762515f88f24b16e23; GCC16.2 4. Exercise broken ^^/splices/templates, unsaved imports, completion/hover/navigation/references and editable origins. Report feature/version matrix, latency/memory, maintenance burden and dependency license facts. ## Failure behavior and constraints -The pinned documentation explicitly excludes constexpr-range expansion used by VoidLibrary; treat that as likely failure requiring proof, not a small assumed workaround. Missing required semantics rejects this sole-engine candidate. Compiler repairs, GCC integration or mixed backends require a new explicit decision and task scope. +The pinned documentation and the pinned libc++ enum-to-string test give conflicting indications on constexpr-range expansion. Run the real Void headers against GCC's standard library to decide fidelity. Missing required semantics rejects this sole-engine candidate. Compiler repairs, GCC integration or mixed backends require a new explicit decision and task scope. ## Acceptance scenarios 1. Compile/analyze exact source fixtures with reference GCC and candidate, retaining diagnostic/AST/query evidence and unsupported-feature classification. diff --git a/docs/roadmap/09-semantic-workers.md b/docs/roadmap/09-semantic-workers.md index f4306d4..9a9b061 100644 --- a/docs/roadmap/09-semantic-workers.md +++ b/docs/roadmap/09-semantic-workers.md @@ -1,6 +1,10 @@ # 09 — Semantic worker protocol and compiler integration -Status: PLANNED; no implementation claim +The opt-in Linux/Nix worker runs stock GCC 16.2 on the workspace-selected TU and +publishes diagnostics over stdio. It reconstructs the compiler's observed +lookup paths in an isolated filesystem, retains positive and negative source +receipts, and checks the context and editor revision before publication. +Persistent AST workers, other toolchain profiles and semantic queries remain open. Requirements: R-007,R-010,R-013,R-014,R-021 Dependencies: 03,04,05 and successful08; shared worker protocol frozen before10-16. diff --git a/docs/roadmap/10-scheduling-resources.md b/docs/roadmap/10-scheduling-resources.md index 5a70b2a..43a35aa 100644 --- a/docs/roadmap/10-scheduling-resources.md +++ b/docs/roadmap/10-scheduling-resources.md @@ -1,6 +1,6 @@ # 10 — Scheduling, cancellation and resource budgets -Status: PLANNED; no implementation claim +Status: A bounded scheduler library with a registered suite is implemented (pools, admission, coalescing, cancellation, watchdog, metrics). Integrating it into the analysis workers remains open. Requirements: R-011,R-021 Dependencies: 03,05,09; coordinates11,15 and18 without sharing mutable compiler state. diff --git a/docs/roadmap/11-cpp-modules.md b/docs/roadmap/11-cpp-modules.md index fbb721b..944e151 100644 --- a/docs/roadmap/11-cpp-modules.md +++ b/docs/roadmap/11-cpp-modules.md @@ -1,6 +1,9 @@ # 11 — Named modules, partitions, header units and artifact ownership -Status: PLANNED; no implementation claim +Status: The GCC reference suite passes 33 module and scanner checks. The +C++ module planner and GCC single-rule P1689 decoder pass 22 cases in native +VBS and CMake. Seven integration cases exercise the planner with the compiler +corpus. The private artifact cache, dependency-ordered production and real GCC CMI production are implemented with registered tests; an editor admission queue for scans and artifacts is implemented and wired into the document lifecycle; the editor now submits the real P1689 scan through that queue; editor-driven artifact production remains open. Requirements: R-008,R-010,R-012,R-021 Dependencies: 05,06/07,08,09,10; generated prerequisites depend on VBS availability. diff --git a/docs/roadmap/12-reflection-provenance.md b/docs/roadmap/12-reflection-provenance.md index 91d82a6..7b1c491 100644 --- a/docs/roadmap/12-reflection-provenance.md +++ b/docs/roadmap/12-reflection-provenance.md @@ -1,6 +1,6 @@ # 12 — Reflection, meta values and generated-source provenance -Status: PLANNED; no implementation claim +Status: PARTIAL; the bounded provenance/value representation library, read-only virtual generated views, splice-origin extraction from the reproduced GCC frontend, LSP-shaped hover/location adapters and the live-DAP reflected-entity projection are implemented with registered suites. `EditorDiagnostics` LSP wiring (the server has no reflection data source) and index/rename integration remain open. Requirements: R-010,R-013,R-014,R-015,R-016 Dependencies: 08,09,11 for module-crossing cases; shared SymbolIdentity with15/16 and events with17. diff --git a/docs/roadmap/13-diagnostics-recovery.md b/docs/roadmap/13-diagnostics-recovery.md index 7e6fffa..f9c7bc8 100644 --- a/docs/roadmap/13-diagnostics-recovery.md +++ b/docs/roadmap/13-diagnostics-recovery.md @@ -1,6 +1,10 @@ # 13 — Diagnostics, freshness and incomplete-edit recovery -Status: PLANNED; no implementation claim +The opt-in stock GCC 16.2 worker publishes verified TU ranges and clears +recovered errors over LSP. An edited Void source, a header overlay, an appearing +optional header and a superseded running compile have stdio coverage. Messages +with unproven locations appear in the per-document analysis status. Cross-file +publication, richer ranges, module scheduling and wider recovery testing remain open. Requirements: R-004,R-006,R-014,R-021 Dependencies: 03,05,09,10;11/12 for module/reflection cases. diff --git a/docs/roadmap/14-completion-hover.md b/docs/roadmap/14-completion-hover.md index b4f03e1..4e35816 100644 --- a/docs/roadmap/14-completion-hover.md +++ b/docs/roadmap/14-completion-hover.md @@ -1,6 +1,6 @@ # 14 — Completion, signatures and hover -Status: PLANNED; no implementation claim +Status: PARTIAL; index-backed `textDocument/completion` and `textDocument/signatureHelp` from the compiler-provided occurrence signature (bounded core, server wiring and registered `vls_feature_tests`) are implemented. Compiler-native completion, visibility proof, deferred detail resolution and signature help for overloads beyond the selected occurrence remain open. Requirements: R-011,R-013,R-014 Dependencies: 03,05,09,10,12;15 supplies workspace candidates after its contract freezes. diff --git a/docs/roadmap/15-index-persistence.md b/docs/roadmap/15-index-persistence.md index 69fe658..813ef0c 100644 --- a/docs/roadmap/15-index-persistence.md +++ b/docs/roadmap/15-index-persistence.md @@ -1,6 +1,6 @@ # 15 — Context-aware symbol index and persistent generations -Status: PLANNED; no implementation claim +Status: A bounded context-aware index library with a registered suite is implemented (contexts, overlays, invalidation, generations, persistence, coverage). It is wired to `workspace/symbol`; migrations, cross-file rename coverage and a persistent backend remain open. Requirements: R-008,R-014,R-015,R-021 Dependencies: 03,05,09,10,12; coordinates16 coverage and11 dependency edges. diff --git a/docs/roadmap/16-navigation-rename.md b/docs/roadmap/16-navigation-rename.md index bf24c65..b388a87 100644 --- a/docs/roadmap/16-navigation-rename.md +++ b/docs/roadmap/16-navigation-rename.md @@ -1,6 +1,6 @@ # 16 — Navigation, references and guarded rename -Status: PLANNED; no implementation claim +Status: A bounded navigation and guarded-rename library with a registered suite is implemented and wired to references/prepareRename/rename. Client buffer-transaction application, cross-context rename coverage and live editor integration remain open. Requirements: R-013,R-014,R-015,R-020 Dependencies: 03,05,09,12,15; guarded application requires22/23 client contracts. diff --git a/docs/roadmap/17-compiler-debug-instrumentation.md b/docs/roadmap/17-compiler-debug-instrumentation.md index 311cffc..2e27af9 100644 --- a/docs/roadmap/17-compiler-debug-instrumentation.md +++ b/docs/roadmap/17-compiler-debug-instrumentation.md @@ -1,6 +1,11 @@ # 17 — Compiler instrumentation and debugger feasibility gate -Status: PLANNED; no implementation claim +Status: Both a stock GCC 16.2 package observed through GDB and the private +GCC prototype demonstrated live nested integral returns on the reflection +fixture. The patched worker also passed cancellation and truncation checks. +Operator-level reflection events, constraint events, and editor controls +remain open. The current results and toolchain identity are in the +[verification record](../agent-workflow/VERIFICATION.md). Requirements: R-010,R-013,R-016,R-017,R-018 Dependencies: Successful08;09/12 DTOs and source provenance; define Gate2 fixture before18-21. diff --git a/docs/roadmap/18-live-debugging.md b/docs/roadmap/18-live-debugging.md index 90698ed..134abcb 100644 --- a/docs/roadmap/18-live-debugging.md +++ b/docs/roadmap/18-live-debugging.md @@ -1,6 +1,6 @@ # 18 — Live metaprogram debugger state and control -Status: PLANNED; no implementation claim +Status: The local GCC hook prototype and an unmodified GCC 16.2/GDB probe both observed nested integral returns after an enum edit. The fixed worker also exercised step, resume, cancellation and cleanup. A LiveSession control core and a live DAP mode (step/continue/cancel, bounded frame inspection with generation-bound handles) are now implemented with registered tests. General reflection, constraint and template inspection, breakpoints and typed value inspection remain open. Requirements: R-016,R-017,R-019,R-021 Dependencies: 09,10,12, successful17; shared sessions with19-21. diff --git a/docs/roadmap/19-trace-replay.md b/docs/roadmap/19-trace-replay.md index 988fa43..e02fd92 100644 --- a/docs/roadmap/19-trace-replay.md +++ b/docs/roadmap/19-trace-replay.md @@ -1,6 +1,6 @@ # 19 — Trace persistence, event-time state and replay -Status: PLANNED; no implementation claim +Status: Both builds pass 13 journal cases and eight immutable recording cases. The standalone DAP adapter reads completed and cancelled sessions without a compiler. Each open recording keeps its original source, frames and acknowledged actions through file replacement or removal. Requirements: R-016,R-018,R-019,R-021 Dependencies: 12,17,18; bounded storage primitives from15 may be reused after their guarantees are checked. diff --git a/docs/roadmap/20-dap-service.md b/docs/roadmap/20-dap-service.md index 83ace0d..611d2f7 100644 --- a/docs/roadmap/20-dap-service.md +++ b/docs/roadmap/20-dap-service.md @@ -1,6 +1,11 @@ # 20 — Debug Adapter Protocol service -Status: PLANNED; no implementation claim +The C++ stdio adapter serves recorded GCC constant evaluations. Standard DAP +clients can launch a selected journal, inspect stack frames, scopes, return +values and captured source, and continue through integral returns. Seven +registered cases and a real-journal transcript exercise lifecycle, error and +source boundaries. A headless Neovim 0.12.6 client reached 17 and 34. Live +compiler control, additional breakpoint kinds and source stepping remain open. Requirements: R-017,R-018,R-019,R-020 Dependencies: 18,19; shared session service with21 and client integrations22/23. diff --git a/docs/roadmap/21-inspection-api.md b/docs/roadmap/21-inspection-api.md index c5df24a..a84b32b 100644 --- a/docs/roadmap/21-inspection-api.md +++ b/docs/roadmap/21-inspection-api.md @@ -1,6 +1,13 @@ # 21 — Shared custom inspection API and view models -Status: PLANNED; no implementation claim +The recorded adapter implements schema version 1 over the same DAP session. +`vls/session` reports the recording outcome and current cursor. Page requests +`vls/timeline` and `vls/frames` take the session ID, schema version, current +generation, start and count. Pages contain up to 256 events or frames. +`vls/seek` moves to a verified event or an adjacent integral result. Every +movement expires the earlier frame, scope and page references. The debugger +retains the captured source for the session. Template and constraint trees, +reflection entities, generated views and live inspection remain open. Requirements: R-013,R-016,R-018,R-019,R-020 Dependencies: 12,18,19,20; contract frozen before independent22/23 view implementations. diff --git a/docs/roadmap/23-neovim-client.md b/docs/roadmap/23-neovim-client.md index 77c30db..83ccd54 100644 --- a/docs/roadmap/23-neovim-client.md +++ b/docs/roadmap/23-neovim-client.md @@ -1,6 +1,9 @@ # 23 — Neovim LSP/DAP integration and inspection buffers -Status: PLANNED; no implementation claim +Headless Neovim 0.12.6 and nvim-dap exercised the recorded adapter through +`dap.run`, `dap.continue` and `Session:disconnect`. The test requested actual +17/34 values, the captured source and the acknowledged timeline. The packaged +Lua client, read-only views and the rest of the editor journeys remain open. Requirements: R-015,R-019,R-020 Dependencies: 02 for basic launch;16,18-21 for full acceptance. May parallel22 after schema freeze. diff --git a/docs/roadmap/26-vbs-self-build-adoption.md b/docs/roadmap/26-vbs-self-build-adoption.md index 94a0be6..ba2c077 100644 --- a/docs/roadmap/26-vbs-self-build-adoption.md +++ b/docs/roadmap/26-vbs-self-build-adoption.md @@ -1,16 +1,16 @@ # 26 — Native VBS build and staged Void adoption -Status: PLANNED; no implementation claim +Status: Native build and tests verified. Dependency-aware VBS development CLI installed a working server. Full editor/project adoption is gated. Requirements: R-008,R-010,R-014,R-020,R-022,R-023 -Dependencies: VBS native executor/toolchain/package/testing readiness;06 live producer,08 semantic gate and core IDE/debug milestones for full replacement. +Dependencies: VBS native executor/toolchain/package/testing readiness and01 for the immediate build slice;06 live producer,08 semantic gate and core IDE/debug milestones for full replacement. ## Ownership and boundaries -Future joint work: root coordinates repository boundaries; Sol VLS build descriptions/adoption harnesses, Astra coupled native-tooling issues. NEW build.cpp/build profiles and tests/adoption/ only after scope approval. +Root coordinates repository boundaries; proposed Sol VLS build descriptions/adoption harnesses and Astra coupled native-tooling issues. NEW build.cpp/build profiles are now authorized by D-025; write ownership and preflight still precede substantial implementation. Future assignments must verify the then-current baseline and exact disjoint paths; these proposed scopes do not authorize work in another repository. ## Contracts and data flow -CMake is the initial seed; native VBS becomes the primary build path after verified readiness. VLS runtime consumes a resolved tooling contract independently of how VLS itself was built. Initial adoption corpus is VoidLibrary plus VBS; all remaining Void projects require explicit inventory and evidence. +Native VBS is the primary build path per D-025. The existing CMake seed provides comparison evidence while native readiness is established. VLS runtime consumes a resolved tooling contract independently of how VLS itself was built. Initial adoption corpus is VoidLibrary plus VBS; all remaining Void projects require explicit inventory and evidence. ## Implementation sequence 1. Map the actual built VLS target/module/test closure into ordinary VBS C++ descriptions after its executor/SDK stabilizes. Keep host compiler and analyzed target toolchain identities distinct. diff --git a/docs/roadmap/README.md b/docs/roadmap/README.md index 30ea29e..f051552 100644 --- a/docs/roadmap/README.md +++ b/docs/roadmap/README.md @@ -1,7 +1,7 @@ # Development roadmap -Approved2026-11-25. This directory contains27 subsystem plans. Only01/02 belong -to the current implementation milestone; all later capabilities require the gates +Approved2026-11-25; full roadmap implementation authorized2026-11-27. This directory +contains27 subsystem plans. Implement them in dependency order with the gates and evidence below. Read [requirements](REQUIREMENTS.md), [architecture](ARCHITECTURE.md) and [current state](../agent-workflow/STATE.md) first. @@ -60,11 +60,17 @@ The diagram is not a promise that native VBS production exists. Its separately owned producer/executor is an explicit prerequisite of06/26 live acceptance. ## Gates and parallel ownership -- M0: documents, CLI/lifecycle shell, unit/subprocess tests; final JSON acceptance - waits for a verified committed VoidLibrary decimal revision. -- G1: actual GCC16/libstdc++ Void fidelity and interactive behavior. Current candidate - likely fails constexpr-range expansion. Failure requires a new explicit decision; - compiler fixes/backend substitution are not silently added. +- D-025 makes native VBS build/test support the immediate priority. Implement the + build portion of26 alongside01; full project/editor adoption still depends on + its semantic/debugger gates. Future CTest labels/commands in individual plans + describe the earlier bootstrap proposal; bind equivalent nonzero native VBS + test targets before implementation. They do not make CMake the primary build. +- M0 covers the CLI, lifecycle and protocol suites. Decimal-capable VoidLibrary + main passes six numeric cases. Two exactness/range cases still fail. +- G1 requires GCC 16/libstdc++ Void fidelity and interactive behavior. The + pinned Clang failed the production-header check. D-028 and D-030 authorize + the private GCC evaluation and versioned hooks. Reference fidelity passes. + Source-occurrence and complete interactive gates are still open. - G2: evaluator+Sema instrumentation, live control and reliable replay on mixed template/constraint/constexpr/reflection cases, including adverse outcomes. - Core and debugger tracks may proceed independently only after their common diff --git a/docs/roadmap/REQUIREMENTS.md b/docs/roadmap/REQUIREMENTS.md index 6fca72d..02dbc98 100644 --- a/docs/roadmap/REQUIREMENTS.md +++ b/docs/roadmap/REQUIREMENTS.md @@ -1,7 +1,8 @@ # Requirements and acceptance ledger -Approved 2026-11-25. Scope approval covers milestone0 (repository, detailed plans, -working shell). The remaining requirements describe gated future delivery. +Approved2026-11-25. On2026-11-27 the user authorized implementing all plans. +The full requirement set remains the goal; completion requires the gates and +evidence below, not just bootstrap test success. | ID | Requirement | Acceptance boundary | Plans | | --- | --- | --- | --- | @@ -26,7 +27,7 @@ working shell). The remaining requirements describe gated future delivery. | R-019 | DAP and custom views | One session/control authority, DAP plus timeline/tree/entity views | 20,21 | | R-020 | Neovim AND VS Code | End-to-end editing, guarded rename, live and replay debug journeys | 22,23 | | R-021 | Robustness and resource isolation | Worker recovery, bounded resources, cancellation and ordinary-editing capacity | 09,10,18,19,24 | -| R-022 | CMake bootstrap then native VBS build | Independent seed now, verified native build later | 01,26 | +| R-022 | Native VBS as primary build system | Build/test/install VLS and VoidLibrary natively; existing CMake seed is historical bootstrap evidence | 01,26 | | R-023 | Staged adoption across Void | VoidLibrary and VBS first; evidence-based expansion to remaining projects | 26 | | R-024 | Linux first; later parity/ports | Linux release matrix now; Windows/macOS and broader IDE features separate | 25,27 | | R-025 | Detailed durable plans and decisions | Dependency graph, contracts, ownership, failures, implementation and tests for every part | All | @@ -43,7 +44,7 @@ The planned C++26 matrix is bounded by the approved GCC16 project corpus and exp enumerated proposals; do not claim complete final-standard coverage from -std=c++26. ## Current external prerequisites -VoidLibrary decimal support is being developed by another worker. Confirm an exact -committed revision and all JSON tests before final shell acceptance. -The VBS resolved tooling producer is planned independently. The frontend and debugger -feasibility experiments have not run. Licensing is intentionally undecided. +VoidLibrary main `7d7d23e` supplies decimal support. Independent review found +two remaining exact-number requirements, now exercised by failing cases. VBS has new editor +generation/query APIs; complete native tooling coverage and live adoption remain +unverified. Frontend/debugger feasibility and licensing remain explicit gates. diff --git a/experiments/frontend/gcc-observer/Observer.cpp b/experiments/frontend/gcc-observer/Observer.cpp new file mode 100644 index 0000000..d8a8c84 --- /dev/null +++ b/experiments/frontend/gcc-observer/Observer.cpp @@ -0,0 +1,724 @@ +// Local stock GCC 16.2 occurrence observer for VLS. +// +// The plugin publishes compiler-owned facts for resolved direct calls and +// actual function definitions in the captured file set. It reads a private +// manifest (fixed path or VLS_OBSERVER_INPUTS on the test leg), verifies every +// physical span against the captured UTF-8 bytes, and writes one strict JSON +// report (fixed path or VLS_OBSERVER_OUTPUT). No tree, line map or parser +// pointer escapes this process. + +#include "gcc-plugin.h" +#include "plugin-version.h" + +#include "cp/cp-tree.h" +#include "cpplib.h" +#include "diagnostic.h" +#include "function.h" +#include "input.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int plugin_is_GPL_compatible; + +namespace { + +constexpr unsigned max_name = 64; +constexpr unsigned max_type = 160; +constexpr unsigned max_signature = 300; +constexpr unsigned max_path = 4095; +constexpr unsigned max_inputs = 1024; +constexpr unsigned max_occurrences = 256; +constexpr std::size_t max_file = 16U * 1024U * 1024U; +constexpr std::size_t max_total = 64U * 1024U * 1024U; +constexpr std::size_t max_manifest = 4U * 1024U * 1024U; +constexpr unsigned max_visited = 200000; + +struct span { + unsigned line{}; + unsigned start{}; + unsigned end{}; + + bool same(const span &other) const { + return line == other.line && start == other.start && end == other.end; + } +}; + +struct file_entry { + char path[max_path + 1]{}; + unsigned char *data{}; + std::size_t size{}; +}; + +struct body_entry { + unsigned uid{}; + span where{}; + char path[max_path + 1]{}; + bool definition{}; + bool conflict{}; +}; + +struct use_entry { + unsigned uid{}; + span where{}; + char path[max_path + 1]{}; + char name[max_name + 1]{}; + char type[max_type + 1]{}; + char canonical[max_type + 1]{}; + char signature[max_signature + 1]{}; + bool conflict{}; +}; + +char nonce[33]; +char primary_path[max_path + 1]; +file_entry files[max_inputs]; +unsigned file_count; +body_entry bodies[max_occurrences]; +unsigned body_count; +use_entry uses[max_occurrences]; +unsigned use_count; +std::size_t total_bytes; +unsigned visited; +bool at_capacity; +bool withheld_origin; +bool withheld_semantics; +bool withheld_conflict; +bool over_walk; + +bool admitted(const char *path) { + if (!path) { + return false; + } + for (unsigned i = 0; i != file_count; ++i) { + if (!std::strcmp(files[i].path, path)) { + return true; + } + } + return false; +} + +file_entry *file_for(const char *path) { + if (!path) { + return nullptr; + } + for (unsigned i = 0; i != file_count; ++i) { + if (!std::strcmp(files[i].path, path)) { + return &files[i]; + } + } + return nullptr; +} + +bool load_file(const char *path) { + if (file_count == max_inputs) { + return false; + } + const int fd = ::open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + if (fd < 0) { + return false; + } + struct stat st{}; + if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size < 0 || + static_cast(st.st_size) > max_file || + total_bytes + static_cast(st.st_size) > max_total) { + ::close(fd); + return false; + } + const auto size = static_cast(st.st_size); + auto *data = static_cast(xmalloc(size ? size : 1)); + if (!data) { + ::close(fd); + return false; + } + std::size_t done = 0; + while (done != size) { + const ssize_t n = ::read(fd, data + done, size - done); + if (n <= 0) { + free(data); + ::close(fd); + return false; + } + done += static_cast(n); + } + ::close(fd); + file_entry &entry = files[file_count++]; + std::strcpy(entry.path, path); + entry.data = data; + entry.size = size; + total_bytes += size; + return true; +} + +bool parse_manifest() { + const char *input = std::getenv("VLS_OBSERVER_INPUTS"); + if (!input || !*input) { + input = "/vls-observer/inputs"; + } + const int fd = ::open(input, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + if (fd < 0) { + return false; + } + char *text = static_cast(xmalloc(max_manifest + 1)); + if (!text) { + ::close(fd); + return false; + } + std::size_t size = 0; + while (size != max_manifest) { + const ssize_t n = ::read(fd, text + size, max_manifest - size); + if (n == 0) { + break; + } + if (n < 0) { + free(text); + ::close(fd); + return false; + } + size += static_cast(n); + } + ::close(fd); + if (size == max_manifest) { + free(text); + return false; + } + text[size] = '\0'; + if (std::strlen(text) != size) { + free(text); + return false; + } + char *lines[max_inputs + 3]; + unsigned count = 0; + char *cursor = text; + while (*cursor) { + if (count == max_inputs + 3) { + free(text); + return false; + } + lines[count++] = cursor; + char *end = std::strchr(cursor, '\n'); + if (!end) { + break; + } + *end = '\0'; + cursor = end + 1; + } + if (count < 3 || std::strcmp(lines[0], "VLS-OCCURRENCES-1") != 0 || + std::strlen(lines[1]) != 32) { + free(text); + return false; + } + for (unsigned i = 0; i != 32; ++i) { + const char c = lines[1][i]; + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) { + free(text); + return false; + } + } + std::strcpy(nonce, lines[1]); + std::strcpy(primary_path, lines[2]); + for (unsigned i = 2; i != count; ++i) { + const std::size_t length = std::strlen(lines[i]); + if (!length || length > max_path || lines[i][0] != '/') { + free(text); + return false; + } + if (!file_for(lines[i]) && !load_file(lines[i])) { + free(text); + return false; + } + } + free(text); + return true; +} + +bool utf8_valid(const char *text) { + const auto *s = reinterpret_cast(text); + while (*s) { + if (*s < 0x80) { + ++s; + } else if ((*s & 0xE0) == 0xC0 && (s[1] & 0xC0) == 0x80) { + if (*s < 0xC2) { + return false; + } + s += 2; + } else if ((*s & 0xF0) == 0xE0 && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80) { + s += 3; + } else if ((*s & 0xF8) == 0xF0 && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80 && + (s[3] & 0xC0) == 0x80) { + s += 4; + } else { + return false; + } + } + return true; +} + +void json_string(std::FILE *out, const char *text) { + std::fputc('"', out); + for (const auto *s = reinterpret_cast(text); *s; ++s) { + switch (*s) { + case '"': + std::fputs("\\\"", out); + break; + case '\\': + std::fputs("\\\\", out); + break; + case '\n': + std::fputs("\\n", out); + break; + case '\r': + std::fputs("\\r", out); + break; + case '\t': + std::fputs("\\t", out); + break; + default: + if (*s < 0x20) { + std::fprintf(out, "\\u%04x", unsigned(*s)); + } else { + std::fputc(*s, out); + } + } + } + std::fputc('"', out); +} + +bool plain_name(tree decl) { + if (!decl || TREE_CODE(decl) != FUNCTION_DECL || DECL_ARTIFICIAL(decl) || !DECL_NAME(decl)) { + return false; + } + if (fndecl_built_in_p(decl) || !TREE_TYPE(decl) || + TREE_CODE(TREE_TYPE(decl)) != FUNCTION_TYPE) { + return false; + } + if (DECL_CONTEXT(decl) && TYPE_P(DECL_CONTEXT(decl))) { + return false; + } + if (DECL_LANG_SPECIFIC(decl) && DECL_TEMPLATE_INFO(decl)) { + return false; + } + tree id = DECL_NAME(decl); + const unsigned length = IDENTIFIER_LENGTH(id); + if (!length || length > max_name) { + return false; + } + const char *name = IDENTIFIER_POINTER(id); + for (unsigned i = 0; i != length; ++i) { + const char c = name[i]; + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || + (i && c >= '0' && c <= '9'))) { + return false; + } + } + return true; +} + +// One-based physical byte columns, end exclusive. GCC columns count bytes but +// a first-line UTF-8 BOM is not part of the column space, so it is restored. +bool token_span(location_t token, unsigned length, const char *expected, span &out, + const char **path_out) { + const location_t start = get_pure_location(get_start(token)); + const location_t last = get_pure_location(get_finish(token)); + if (RESERVED_LOCATION_P(start) || RESERVED_LOCATION_P(last) || + get_pure_location(token) != start || from_macro_expansion_at(start) || + from_macro_expansion_at(last)) { + return false; + } + const line_map *raw_map = linemap_lookup(line_table, start); + if (!raw_map || !MAP_ORDINARY_P(raw_map) || linemap_lookup(line_table, last) != raw_map) { + return false; + } + const line_map_ordinary *map = linemap_check_ordinary(raw_map); + if (map->sysp || !map->to_file) { + return false; + } + file_entry *file = file_for(map->to_file); + if (!file) { + return false; + } + const unsigned line = SOURCE_LINE(map, start); + const unsigned column = SOURCE_COLUMN(map, start); + const unsigned final = SOURCE_COLUMN(map, last); + if (!line || !column || SOURCE_LINE(map, last) != line || final == UINT_MAX || final < column || + final - column + 1 != length) { + return false; + } + std::size_t line_start = 0; + for (unsigned current = 1; current != line; ++current) { + const void *newline = std::memchr(file->data + line_start, '\n', file->size - line_start); + if (!newline) { + return false; + } + line_start = + static_cast(static_cast(newline) - file->data) + 1; + } + const bool bom = line == 1 && file->size >= 3 && file->data[0] == 0xEF && + file->data[1] == 0xBB && file->data[2] == 0xBF; + const std::size_t shift = bom ? 3 : 0; + const std::size_t begin = line_start + shift + column - 1; + if (begin + length > file->size || std::memcmp(file->data + begin, expected, length) != 0) { + return false; + } + out = {line, column + unsigned(shift), column + unsigned(shift) + length}; + *path_out = file->path; + return true; +} + +bool range_bytes(location_t location, file_entry *&file, std::size_t &begin, std::size_t &end) { + const location_t start = get_pure_location(get_start(location)); + const location_t last = get_pure_location(get_finish(location)); + if (RESERVED_LOCATION_P(start) || RESERVED_LOCATION_P(last) || from_macro_expansion_at(start) || + from_macro_expansion_at(last)) { + return false; + } + const line_map *raw_map = linemap_lookup(line_table, start); + if (!raw_map || !MAP_ORDINARY_P(raw_map) || linemap_lookup(line_table, last) != raw_map) { + return false; + } + const line_map_ordinary *map = linemap_check_ordinary(raw_map); + if (map->sysp || !map->to_file) { + return false; + } + file = file_for(map->to_file); + if (!file) { + return false; + } + const unsigned line = SOURCE_LINE(map, start); + const unsigned column = SOURCE_COLUMN(map, start); + const unsigned final = SOURCE_COLUMN(map, last); + if (!line || !column || SOURCE_LINE(map, last) != line || final < column) { + return false; + } + std::size_t line_start = 0; + for (unsigned current = 1; current != line; ++current) { + const void *newline = std::memchr(file->data + line_start, '\n', file->size - line_start); + if (!newline) { + return false; + } + line_start = + static_cast(static_cast(newline) - file->data) + 1; + } + const bool bom = line == 1 && file->size >= 3 && file->data[0] == 0xEF && + file->data[1] == 0xBB && file->data[2] == 0xBF; + const std::size_t shift = bom ? 3 : 0; + begin = line_start + shift + column - 1; + end = line_start + shift + final; + return begin < end && end <= file->size; +} + +bool identifier_char(unsigned char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; +} + +// Isolate the terminal identifier before the first '(' inside the call range. +bool call_token(tree call, tree decl, span &out, const char **path_out) { + const location_t location = EXPR_LOCATION(call); + if (location == UNKNOWN_LOCATION) { + return false; + } + file_entry *file = nullptr; + std::size_t begin = 0; + std::size_t end = 0; + if (!range_bytes(location, file, begin, end)) { + return false; + } + std::size_t open = begin; + while (open != end && file->data[open] != '(') { + ++open; + } + if (open == end) { + return false; + } + std::size_t stop = open; + while (stop != begin && (file->data[stop - 1] == ' ' || file->data[stop - 1] == '\t')) { + --stop; + } + std::size_t start = stop; + while (start != begin && identifier_char(file->data[start - 1])) { + --start; + } + const unsigned length = IDENTIFIER_LENGTH(DECL_NAME(decl)); + if (stop - start != length || + std::memcmp(file->data + start, IDENTIFIER_POINTER(DECL_NAME(decl)), length) != 0) { + return false; + } + // The conservative grammar admits one physical line for the callee prefix. + if (std::memchr(file->data + begin, '\n', start - begin)) { + return false; + } + unsigned line = 1; + std::size_t line_start = 0; + for (std::size_t i = 0; i != start; ++i) { + if (file->data[i] == '\n') { + ++line; + line_start = i + 1; + } + } + if (line_start > start || start - line_start > UINT_MAX - 1) { + return false; + } + out = {line, unsigned(start - line_start + 1), unsigned(stop - line_start + 1)}; + *path_out = file->path; + return true; +} + +body_entry *find_body(unsigned uid) { + for (unsigned i = 0; i != body_count; ++i) { + if (bodies[i].uid == uid) { + return &bodies[i]; + } + } + return nullptr; +} + +void record_body(tree decl) { + if (!plain_name(decl) || at_capacity) { + return; + } + const location_t location = DECL_SOURCE_LOCATION(decl); + if (RESERVED_LOCATION_P(location) || from_macro_expansion_at(get_pure_location(location))) { + return; + } + span where; + const char *path = nullptr; + if (!token_span(location, IDENTIFIER_LENGTH(DECL_NAME(decl)), + IDENTIFIER_POINTER(DECL_NAME(decl)), where, &path)) { + withheld_origin = true; + return; + } + const unsigned uid = DECL_UID(decl); + if (body_entry *old = find_body(uid)) { + if (!old->where.same(where)) { + old->conflict = true; + withheld_conflict = true; + } + old->definition = true; + return; + } + if (body_count == max_occurrences) { + at_capacity = true; + return; + } + body_entry &entry = bodies[body_count++]; + entry.uid = uid; + entry.where = where; + std::strcpy(entry.path, path); + entry.definition = true; +} + +void record_use(tree call, tree decl) { + if (at_capacity) { + return; + } + if (!plain_name(decl)) { + withheld_semantics = true; + return; + } + const tree type = TREE_TYPE(call); + if (!type || type == error_mark_node) { + withheld_semantics = true; + return; + } + span where; + const char *path = nullptr; + if (!call_token(call, decl, where, &path)) { + withheld_origin = true; + return; + } + const char *type_text = type_as_string(type, TFF_SCOPE); + const tree canonical_type = TYPE_CANONICAL(type) ? TYPE_CANONICAL(type) : type; + const char *canonical_text = type_as_string(canonical_type, TFF_SCOPE); + if (!type_text || !canonical_text || std::strlen(type_text) > max_type || + std::strlen(canonical_text) > max_type || !utf8_valid(type_text) || + !utf8_valid(canonical_text) || !utf8_valid(path)) { + withheld_semantics = true; + return; + } + const unsigned uid = DECL_UID(decl); + for (unsigned i = 0; i != use_count; ++i) { + if (!uses[i].where.same(where)) { + continue; + } + if (uses[i].uid != uid || std::strcmp(uses[i].type, type_text) != 0 || + std::strcmp(uses[i].canonical, canonical_text) != 0) { + uses[i].conflict = true; + withheld_conflict = true; + } + return; + } + if (use_count == max_occurrences) { + at_capacity = true; + return; + } + use_entry &entry = uses[use_count++]; + entry.uid = uid; + entry.where = where; + std::strcpy(entry.path, path); + std::memcpy(entry.name, IDENTIFIER_POINTER(DECL_NAME(decl)), + IDENTIFIER_LENGTH(DECL_NAME(decl))); + std::strcpy(entry.type, type_text); + std::strcpy(entry.canonical, canonical_text); + const char *signature = decl_as_string(decl, TFF_SCOPE | TFF_RETURN_TYPE); + if (signature && std::strlen(signature) <= max_signature && utf8_valid(signature)) { + std::strcpy(entry.signature, signature); + } +} + +tree scan(tree *slot, int *walk_subtrees, void *) { + tree node = *slot; + if (!node) { + return NULL_TREE; + } + if (over_walk || ++visited > max_visited) { + over_walk = true; + *walk_subtrees = 0; + return NULL_TREE; + } + if (TYPE_P(node) || DECL_P(node)) { + *walk_subtrees = 0; + return NULL_TREE; + } + if (TREE_CODE(node) != CALL_EXPR) { + return NULL_TREE; + } + tree decl = cp_get_callee_fndecl_nofold(node); + if (decl && plain_name(decl)) { + record_use(node, decl); + } else if (decl) { + withheld_semantics = true; + } + return NULL_TREE; +} + +void started(void *data, void *) { + auto *decl = static_cast(data); + if (!decl || TREE_CODE(decl) != FUNCTION_DECL || !plain_name(decl)) { + return; + } + if (DECL_LANG_SPECIFIC(decl) && DECL_USE_TEMPLATE(decl)) { + return; + } + record_body(decl); +} + +void pre_genericize(void *data, void *) { + auto *decl = static_cast(data); + if (!decl || TREE_CODE(decl) != FUNCTION_DECL || !plain_name(decl) || !DECL_SAVED_TREE(decl)) { + return; + } + if (DECL_LANG_SPECIFIC(decl) && DECL_USE_TEMPLATE(decl)) { + return; + } + if (body_entry *body = find_body(DECL_UID(decl))) { + body->definition = true; + } + const location_t location = DECL_SOURCE_LOCATION(decl); + if (RESERVED_LOCATION_P(location)) { + return; + } + const expanded_location expanded = expand_location(location); + if (!admitted(expanded.file)) { + return; + } + cp_walk_tree_without_duplicates(&DECL_SAVED_TREE(decl), scan, nullptr); +} + +void finish(void *, void *) { + const char *output = std::getenv("VLS_OBSERVER_OUTPUT"); + if (!output || !*output) { + output = "/vls-observer/report"; + } + const char *reason = ""; + bool complete = true; + if (line_table->seen_line_directive) { + reason = "lineDirective"; + complete = false; + } else if (seen_error()) { + reason = "compileErrors"; + complete = false; + } else if (at_capacity || over_walk) { + reason = "capacity"; + complete = false; + } + const int fd = ::open(output, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); + if (fd < 0) { + return; + } + std::FILE *out = ::fdopen(fd, "w"); + if (!out) { + ::close(fd); + return; + } + std::fputs("{\"schema\":1,\"nonce\":", out); + json_string(out, nonce); + std::fprintf(out, ",\"complete\":%s,\"partial\":%s,\"reason\":", complete ? "true" : "false", + (withheld_origin || withheld_semantics || withheld_conflict) ? "true" : "false"); + json_string(out, reason); + std::fputs(",\"occurrences\":[", out); + bool first = true; + if (complete) { + for (unsigned i = 0; i != use_count; ++i) { + const use_entry &use = uses[i]; + if (use.conflict) { + continue; + } + const body_entry *body = find_body(use.uid); + const bool known = body && !body->conflict; + if (!first) { + std::fputc(',', out); + } + first = false; + std::fputs("{\"name\":", out); + json_string(out, use.name); + std::fputs(",\"type\":", out); + json_string(out, use.type); + std::fputs(",\"canonicalType\":", out); + json_string(out, use.canonical); + if (use.signature[0]) { + std::fputs(",\"signature\":", out); + json_string(out, use.signature); + } + std::fputs(",\"use\":{\"path\":", out); + json_string(out, use.path); + std::fprintf(out, ",\"line\":%u,\"startByte\":%u,\"endByte\":%u},\"definition\":", + use.where.line, use.where.start, use.where.end); + if (known) { + std::fputs("{\"path\":", out); + json_string(out, body->path); + std::fprintf(out, ",\"line\":%u,\"startByte\":%u,\"endByte\":%u}", body->where.line, + body->where.start, body->where.end); + } else { + std::fputs("null", out); + } + std::fputc('}', out); + } + } + std::fputs("]}\n", out); + if (std::fflush(out) != 0 || std::ferror(out) || ::fsync(fd) != 0) { + std::fclose(out); + return; + } + std::fclose(out); +} + +} // namespace + +int plugin_init(struct plugin_name_args *info, struct plugin_gcc_version *version) { + if (!plugin_default_version_check(version, &gcc_version)) { + return 1; + } + if (!parse_manifest()) { + return 1; + } + register_callback(info->base_name, PLUGIN_START_PARSE_FUNCTION, started, nullptr); + register_callback(info->base_name, PLUGIN_PRE_GENERICIZE, pre_genericize, nullptr); + register_callback(info->base_name, PLUGIN_FINISH, finish, nullptr); + return 0; +} diff --git a/experiments/frontend/gcc-worker/Leaf.cpp b/experiments/frontend/gcc-worker/Leaf.cpp new file mode 100644 index 0000000..71da072 --- /dev/null +++ b/experiments/frontend/gcc-worker/Leaf.cpp @@ -0,0 +1,275 @@ +#include "Leaf.hpp" + +#include + +#ifdef __linux__ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// GNU ELF linkers expose the native executable header, including class, byte order and machine. +extern "C" const ElfW(Ehdr) __ehdr_start; + +namespace vls::gcc { +namespace { +using Void::System::OwnedFd; +namespace File = Void::LanguageServer::Detail; + +constexpr std::size_t mib = 1024 * 1024; +constexpr std::size_t max_image = 256 * mib; +constexpr int control_fd = 3; +constexpr int events_fd = 4; +constexpr int setup_failure = 126; + +bool lower_hex(std::string_view text, std::size_t size) { + return text.size() == size && std::ranges::all_of(text, [](char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + }); +} + +bool pipe_end(int fd, int mode, struct stat &st) { + const int flags = ::fcntl(fd, F_GETFL); + return flags >= 0 && (flags & (O_ACCMODE | O_PATH)) == mode && ::fstat(fd, &st) == 0 && + S_ISFIFO(st.st_mode); +} + +bool same_object(const struct stat &a, const struct stat &b) { + return a.st_dev == b.st_dev && a.st_ino == b.st_ino; +} + +int fail(const char *reason, int error = 0) noexcept { + // Even an invalid stdio setup must never put diagnostic bytes on the event/control channel. + struct stat err{}, other{}; + if (!pipe_end(STDERR_FILENO, O_WRONLY, err)) + return setup_failure; + for (int fd : {STDIN_FILENO, STDOUT_FILENO}) { + if (::fstat(fd, &other) == 0 && same_object(err, other)) + return setup_failure; + } + // The supervisor may have already closed or stopped draining its diagnostics pipe. + const int flags = ::fcntl(STDERR_FILENO, F_GETFL); + if (flags >= 0 && ::fcntl(STDERR_FILENO, F_SETFL, flags | O_NONBLOCK) == 0 && + ::signal(SIGPIPE, SIG_IGN) != SIG_ERR) { + char message[160]; + const int n = error ? std::snprintf(message, sizeof message, "gcc leaf: %s (errno %d)\n", + reason, error) + : std::snprintf(message, sizeof message, "gcc leaf: %s\n", reason); + if (n > 0 && static_cast(n) < sizeof message) + (void)::write(STDERR_FILENO, message, static_cast(n)); + } + return setup_failure; +} + +bool reset_signals() { + struct sigaction action{}; + action.sa_handler = SIG_DFL; + ::sigemptyset(&action.sa_mask); + for (int sig : {SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGPIPE, SIGXCPU, SIGXFSZ}) { + if (::sigaction(sig, &action, nullptr) != 0) + return false; + } + return ::sigprocmask(SIG_SETMASK, &action.sa_mask, nullptr) == 0; +} + +bool cap_resource(int resource, rlim_t soft, rlim_t hard) { + struct rlimit limit{}; + if (::getrlimit(resource, &limit) != 0) + return false; + limit.rlim_cur = std::min(limit.rlim_cur, soft); + limit.rlim_max = std::min(limit.rlim_max, hard); + return ::setrlimit(resource, &limit) == 0; +} + +bool write_chunk(int fd, std::span bytes) { + while (!bytes.empty()) { + const ssize_t count = ::write(fd, bytes.data(), bytes.size()); + if (count < 0 && errno == EINTR) + continue; + if (count <= 0) + return false; + bytes = bytes.subspan(static_cast(count)); + } + return true; +} + +bool complete_native_elf(std::span image) { + const auto fits = [&](std::uint64_t offset, std::uint64_t size) { + return offset <= image.size() && size <= image.size() - offset; + }; + ElfW(Ehdr) header{}; + if (image.size() < sizeof header) + return false; + std::memcpy(&header, image.data(), sizeof header); + if (std::memcmp(header.e_ident, __ehdr_start.e_ident, EI_VERSION + 1) != 0 || + header.e_machine != __ehdr_start.e_machine || header.e_version != EV_CURRENT || + (header.e_type != ET_EXEC && header.e_type != ET_DYN) || header.e_ehsize != sizeof header || + header.e_phoff < sizeof header || header.e_phentsize != sizeof(ElfW(Phdr)) || + !header.e_phnum || header.e_phnum == PN_XNUM || + !fits(header.e_phoff, sizeof(ElfW(Phdr)) * header.e_phnum)) + return false; + + // A truncated section table can leave an otherwise runnable prefix of the file. + if (header.e_shoff || header.e_shnum || header.e_shstrndx) { + if (header.e_shoff < sizeof header || !header.e_shnum || + header.e_shstrndx >= header.e_shnum || header.e_shentsize != sizeof(ElfW(Shdr)) || + !fits(header.e_shoff, sizeof(ElfW(Shdr)) * header.e_shnum)) + return false; + for (unsigned i = 0; i < header.e_shnum; ++i) { + ElfW(Shdr) section{}; + std::memcpy(§ion, image.data() + header.e_shoff + i * sizeof section, + sizeof section); + if (section.sh_type != SHT_NOBITS && !fits(section.sh_offset, section.sh_size)) + return false; + } + } + bool has_entry = false; + for (unsigned i = 0; i < header.e_phnum; ++i) { + ElfW(Phdr) segment{}; + std::memcpy(&segment, image.data() + header.e_phoff + i * sizeof segment, sizeof segment); + if (segment.p_filesz && !fits(segment.p_offset, segment.p_filesz)) + return false; + if (segment.p_type != PT_LOAD) + continue; + if (segment.p_filesz > segment.p_memsz) + return false; + if ((segment.p_flags & PF_X) && header.e_entry >= segment.p_vaddr && + header.e_entry - segment.p_vaddr < segment.p_filesz) + has_entry = true; + } + return has_entry; +} + +const char *verify_bytes(std::span image, std::string_view expected) { + if (!complete_native_elf(image)) + return "incomplete or unsupported native ELF"; + const auto digest = Void::Crypto::hash(Void::Crypto::HashAlgorithm::Sha256, image, + {.prefer_builtin = true}); + if (!digest || digest->size() != 32) + return "SHA-256 unavailable"; + constexpr std::string_view alphabet = "0123456789abcdef"; + for (std::size_t i = 0; i < digest->size(); ++i) { + const auto byte = std::to_integer((*digest)[i]); + if (expected[2 * i] != alphabet[byte >> 4] || expected[2 * i + 1] != alphabet[byte & 15]) + return "compiler SHA-256 mismatch"; + } + return nullptr; +} + +int prepare_image(int image, const std::filesystem::path &compiler, std::string_view expected) { + const open_how how{.flags = O_PATH | O_CLOEXEC, .mode = 0, .resolve = RESOLVE_NO_SYMLINKS}; + const OwnedFd source{static_cast(::syscall(SYS_openat2, AT_FDCWD, compiler.c_str(), + &how, sizeof how))}; + struct stat before{}; + if (!source || ::fstat(source.get(), &before) != 0) + return fail("cannot open direct compiler path with openat2", errno); + if (!S_ISREG(before.st_mode) || before.st_size <= 0 || + static_cast(before.st_size) > max_image) + return fail("expected a nonempty regular compiler within the image limit"); + struct rlimit file_limit{}; + if (::getrlimit(RLIMIT_FSIZE, &file_limit) != 0 || + static_cast(before.st_size) > file_limit.rlim_cur) + return fail("inherited file-size limit cannot hold the compiler"); + const auto copied = File::stream_regular_fd(source, before, max_image, true, [&](auto chunk) { + return write_chunk(image, chunk); + }); + if (!copied) + return fail("failed to capture stable executable compiler"); + + constexpr int seals = F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_EXEC | F_SEAL_SEAL; + if (::fchmod(image, S_IRUSR | S_IXUSR) != 0 || ::fcntl(image, F_ADD_SEALS, seals) != 0) + return fail("kernel refused to seal the compiler memfd", errno); + struct stat sealed{}; + if (::fstat(image, &sealed) != 0 || sealed.st_size != before.st_size) + return fail("sealed compiler size changed"); + + // Hash the sealed object itself. A concurrent source rewrite or pathname exchange cannot + // change the bytes inspected here or the ELF the kernel will load. + const auto size = static_cast(sealed.st_size); + void *mapping = ::mmap(nullptr, size, PROT_READ, MAP_PRIVATE, image, 0); + if (mapping == MAP_FAILED) + return fail("cannot map sealed compiler", errno); + struct Mapping { + void *address; + std::size_t size; + ~Mapping() { ::munmap(address, size); } + } view{mapping, size}; + const auto *error = verify_bytes({static_cast(mapping), size}, expected); + return error ? fail(error) : 0; +} +} // namespace + +int run_leaf(std::filesystem::path compiler, std::string_view expected_sha256, + std::string_view nonce, bool stepping) try { + struct stat in{}, out{}, err{}; + if (!pipe_end(STDIN_FILENO, O_RDONLY, in) || !pipe_end(STDOUT_FILENO, O_WRONLY, out) || + !pipe_end(STDERR_FILENO, O_WRONLY, err) || same_object(in, out) || same_object(in, err) || + same_object(out, err)) + return fail("expected three distinct directed pipes"); + if (!lower_hex(nonce, 32) || !lower_hex(expected_sha256, 64)) + return fail("invalid nonce or SHA-256"); + if (!File::valid_path(compiler) || !compiler.is_absolute()) + return fail("expected an absolute compiler path"); + + const OwnedFd control{::dup2(STDIN_FILENO, control_fd)}; + const OwnedFd events{::dup2(STDOUT_FILENO, events_fd)}; + if (!control || !events || ::fcntl(STDERR_FILENO, F_SETFD, 0) != 0 || + ::close_range(events_fd + 1, UINT_MAX, 0) != 0) + return fail("cannot isolate inherited descriptors", errno); + const OwnedFd null{::open("/dev/null", O_RDWR | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; + struct stat device{}; + if (!null || ::fstat(null.get(), &device) != 0 || !S_ISCHR(device.st_mode) || + device.st_rdev != makedev(1, 3) || ::dup2(null.get(), STDIN_FILENO) < 0 || + ::dup2(null.get(), STDOUT_FILENO) < 0) + return fail("cannot isolate raw compiler stdio"); + if (!reset_signals() || !cap_resource(RLIMIT_CORE, 0, 0) || + !cap_resource(RLIMIT_AS, 768 * mib, 768 * mib) || !cap_resource(RLIMIT_CPU, 15, 20) || + !cap_resource(RLIMIT_NOFILE, 32, 32)) + return fail("cannot set compiler signals or resource limits", errno); + + const OwnedFd image{::memfd_create("vls-cc1plus", MFD_CLOEXEC | MFD_ALLOW_SEALING | MFD_EXEC)}; + if (!image) + return fail("executable memfd unsupported or denied", errno); + if (const int status = prepare_image(image.get(), compiler, expected_sha256)) + return status; + if (!cap_resource(RLIMIT_FSIZE, mib, mib)) + return fail("cannot set compiler output limit", errno); + + char nonce_env[] = "VLS_GCC_NONCE=00000000000000000000000000000000"; + std::memcpy(nonce_env + sizeof("VLS_GCC_NONCE=") - 1, nonce.data(), nonce.size()); + const char *environment[] = {"LC_ALL=C", "PATH=", nonce_env, nullptr}; + const char *arguments[] = {"cc1plus", "-quiet", "-std=c++26", "-freflection", "-fsyntax-only", + "-nostdinc", "-o", "/dev/null", "-fvls-observe", + stepping ? "-fvls-step" : "input.cpp", stepping ? "input.cpp" : nullptr, + nullptr}; + ::execveat(image.get(), "", const_cast(arguments), + const_cast(environment), AT_EMPTY_PATH); + return fail("execveat of sealed compiler failed", errno); +} catch (...) { + return fail("compiler image setup failed"); +} +} // namespace vls::gcc +#else +int vls::gcc::run_leaf(std::filesystem::path, std::string_view, std::string_view, bool) { + std::fputs("gcc leaf: Linux executable memfd support is required\n", stderr); + return 126; +} +#endif diff --git a/experiments/frontend/gcc-worker/Leaf.hpp b/experiments/frontend/gcc-worker/Leaf.hpp new file mode 100644 index 0000000..2420502 --- /dev/null +++ b/experiments/frontend/gcc-worker/Leaf.hpp @@ -0,0 +1,13 @@ +#pragma once + +#include +#include + +namespace vls::gcc { + +// Call only in the dedicated --leaf child, with cwd set to the private input.cpp directory. +// Success replaces the process. On setup failure the child must exit with the returned status. +[[nodiscard]] int run_leaf(std::filesystem::path compiler, std::string_view expected_sha256, + std::string_view nonce, bool stepping); + +} // namespace vls::gcc diff --git a/experiments/frontend/gcc-worker/Main.cpp b/experiments/frontend/gcc-worker/Main.cpp new file mode 100644 index 0000000..1ff4f5d --- /dev/null +++ b/experiments/frontend/gcc-worker/Main.cpp @@ -0,0 +1,67 @@ +#include "Leaf.hpp" +#include "Supervisor.hpp" +#include "Trace.hpp" + +#include +#include +#include + +namespace { +constexpr std::string_view usage = + "vls_gcc_probe run COMPILER SHA256 SOURCE NEW_TRACE [--step]\n" + "vls_gcc_probe replay TRACE [EVENT_SEQUENCE]\n" + "At a stop, send NONCE STOP inspect|step|continue|cancel and a newline.\n" + "During a stepped run, NONCE cancel cancels the running frontend.\n"; +} + +int main(int argc, char **argv) try { + using namespace vls::gcc; + const std::string_view mode = argc >= 2 ? argv[1] : ""; + if (mode == "--leaf" && argc == 6) { + const std::string_view action{argv[5]}; + if (action != "step" && action != "observe") + return 126; + return run_leaf(argv[2], argv[3], argv[4], action == "step"); + } + if (mode == "--help" && argc == 2) { + std::cout << usage; + return 0; + } + std::signal(SIGPIPE, SIG_IGN); + if (mode == "run" && (argc == 6 || (argc == 7 && std::string_view(argv[6]) == "--step"))) { + RunOptions options{std::filesystem::absolute(argv[2]), argv[3], + std::filesystem::absolute(argv[4]), std::filesystem::absolute(argv[5]), + argc == 7}; + auto result = run_session(options); + if (!result) { + std::cerr << "vls_gcc_probe: " << result.error() << '\n'; + return 1; + } + return *result; + } + if (mode == "replay" && (argc == 3 || argc == 4)) { + std::optional sequence; + if (argc == 4) { + const std::string_view text{argv[3]}; + const auto end = text.data() + text.size(); + auto [last, error] = std::from_chars(text.data(), end, sequence.emplace()); + if (error != std::errc{} || last != end) + return 2; + } + auto snapshot = replay(std::filesystem::absolute(argv[2]), sequence); + if (!snapshot) { + std::cerr << "vls_gcc_probe: " << snapshot.error() << '\n'; + return 1; + } + auto json = Protocol::serialize_json(*snapshot); + if (!json) + return 1; + std::cout << *json << '\n'; + return std::cout ? 0 : 1; + } + std::cerr << usage; + return 2; +} catch (const std::exception &error) { + std::cerr << "vls_gcc_probe: " << error.what() << '\n'; + return 1; +} diff --git a/experiments/frontend/gcc-worker/Supervisor.cpp b/experiments/frontend/gcc-worker/Supervisor.cpp new file mode 100644 index 0000000..3b0eca4 --- /dev/null +++ b/experiments/frontend/gcc-worker/Supervisor.cpp @@ -0,0 +1,374 @@ +#include "Supervisor.hpp" +#include "Trace.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::gcc { +namespace { +using namespace std::chrono_literals; +using Clock = std::chrono::steady_clock; +using Protocol::Json; +using Void::Process::Child; +constexpr std::size_t source_limit = 256 * 1024; +constexpr std::size_t diagnostic_limit = 256 * 1024; +volatile std::sig_atomic_t interrupted = 0; +void interrupt(int) { interrupted = 1; } + +std::expected make_nonce() { + std::array bytes{}; + for (std::size_t used = 0; used < bytes.size();) { + const auto n = ::getrandom(bytes.data() + used, bytes.size() - used, 0); + if (n < 0 && errno == EINTR) + continue; + if (n <= 0) + return std::unexpected{"cannot create a session nonce"}; + used += static_cast(n); + } + std::string nonce; + constexpr std::string_view alphabet = "0123456789abcdef"; + for (const auto byte : bytes) { + nonce += alphabet[byte >> 4]; + nonce += alphabet[byte & 15]; + } + return nonce; +} + +class Nonblocking { + public: + explicit Nonblocking(int fd) : fd_(fd), flags_(::fcntl(fd, F_GETFL)) { + ok = flags_ >= 0 && ::fcntl(fd, F_SETFL, flags_ | O_NONBLOCK) == 0; + } + ~Nonblocking() { + if (ok) + ::fcntl(fd_, F_SETFL, flags_); + } + Nonblocking(const Nonblocking &) = delete; + bool ok{}; + private: + int fd_, flags_; +}; + +bool write_bounded(int fd, std::string_view bytes) { + const auto deadline = Clock::now() + 200ms; + while (!bytes.empty() && Clock::now() < deadline) { + const auto n = ::write(fd, bytes.data(), bytes.size()); + if (n > 0) { + bytes.remove_prefix(static_cast(n)); + continue; + } + if (n < 0 && errno == EINTR) + continue; + if (n >= 0 || (errno != EAGAIN && errno != EWOULDBLOCK)) + return false; + pollfd p{fd, POLLOUT, 0}; + if (::poll(&p, 1, 10) < 0 && errno != EINTR) + return false; + } + return bytes.empty(); +} + +bool notice(Json::Object fields) { + auto encoded = Protocol::serialize_json(Json{std::move(fields)}); + if (!encoded || encoded->size() > 65535) + return false; + encoded->push_back('\n'); + return write_bounded(STDOUT_FILENO, *encoded); +} + +struct Pump { + Child &child; + Trace &trace; + const std::string &nonce; + const bool interactive; + std::string diagnostics, event_line, control_line, error; + std::optional status; + std::optional control_origin; + std::optional stopped_at, reaped_at, command_deadline; + Clock::time_point running_since = Clock::now(); + Clock::duration running_time{}; + bool saw_hello{}, events_open{true}, diagnostics_open{true}, controls_open{interactive}; + std::string outcome; + unsigned rejected{}; + + Pump(Child &child, Trace &trace, const std::string &nonce, bool interactive) + : child(child), trace(trace), nonce(nonce), interactive(interactive) {} + + void stop(std::string_view state, std::string reason) { + if (outcome.empty()) { + outcome = state; + error = std::move(reason); + } + } + + void accept_event() { + auto accepted = trace.event(event_line); + if (!accepted) + return stop("truncated", accepted.error()); + auto json = Protocol::parse_json(event_line); + const auto *obj = json ? Protocol::as_object(&*json) : nullptr; + const auto *kind = obj ? Protocol::as_string(Protocol::find_member(*obj, "kind")) : nullptr; + if (!kind) + return stop("truncated", "event lacks a kind"); + if (*kind == "hello") { + saw_hello = true; + if (!notice({{"kind", Json{std::string{"started"}}}, {"nonce", Json{nonce}}, + {"pid", Json{static_cast(child.pid())}}})) + stop("cancelled", "client output closed"); + } else if (*kind == "stopped") { + const auto seq = trace.stopped(); + if (!interactive || !seq || stopped_at) + return stop("truncated", "unexpected compiler stop"); + const auto now = Clock::now(); + running_time += now - running_since; + stopped_at = now; + if (!notice({{"kind", Json{std::string{"stopped"}}}, {"nonce", Json{nonce}}, + {"stop", Json{static_cast(*seq)}}})) + stop("cancelled", "client output closed"); + } else if (*kind == "resumed" || *kind == "terminal") { + command_deadline.reset(); + if (stopped_at) { + stopped_at.reset(); + running_since = Clock::now(); + } + } + } + + void reject() { + if (++rejected >= 32 || !notice({{"kind", Json{std::string{"rejected"}}}})) + stop("cancelled", "control limit or client disconnect"); + } + + void control(std::string_view line) { + const auto space = line.find(' '); + if (space == line.npos || line.substr(0, space) != nonce) + return reject(); + line.remove_prefix(space + 1); + if (line == "cancel" && !stopped_at) + return stop("cancelled", "cancelled while running"); + const auto split = line.find(' '); + if (split == line.npos || !stopped_at || command_deadline) + return reject(); + std::uint32_t seq{}; + const auto [end, ec] = std::from_chars(line.data(), line.data() + split, seq); + const auto action = line.substr(split + 1); + if (ec != std::errc{} || end != line.data() + split || seq != control_origin || + seq != trace.stopped() || (split > 1 && line.front() == '0')) + return reject(); + if (action == "inspect") { + auto snapshot = trace.inspection(); + auto encoded = Protocol::serialize_json(snapshot); + if (!encoded || encoded->size() > 64000) { + if (!notice({{"kind", Json{std::string{"inspectionLimit"}}}, + {"stop", Json{static_cast(seq)}}})) + stop("cancelled", "client output closed"); + } else if (!notice({{"kind", Json{std::string{"inspection"}}}, + {"snapshot", std::move(snapshot)}})) { + stop("cancelled", "client output closed"); + } + return; + } + if (action != "step" && action != "continue" && action != "cancel") + return reject(); + auto accepted = trace.authorize(seq, action); + if (!accepted) + return stop("failed", accepted.error()); + command_deadline = Clock::now() + 2s; + if (!write_bounded(child.stdin_fd(), nonce + " " + std::string{line} + "\n")) + stop("truncated", "compiler control pipe closed"); + } + + enum class Channel { client, events, diagnostics }; + void read_ready(Channel channel, int fd) { + std::array bytes{}; + const auto n = ::read(fd, bytes.data(), bytes.size()); + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) + return; + if (n < 0) + return stop("truncated", "failed to read session pipe"); + if (n == 0) { + if (channel == Channel::client) { + controls_open = false; + if (!status && !trace.ended() && trace.terminal().empty()) + stop("cancelled", "control client disconnected"); + } else if (channel == Channel::events) { + events_open = false; + if (!event_line.empty()) + stop("truncated", "incomplete compiler event"); + } else { + diagnostics_open = false; + } + return; + } + const std::string_view data{bytes.data(), static_cast(n)}; + if (channel == Channel::diagnostics) { + const auto room = diagnostic_limit - diagnostics.size(); + diagnostics.append(data.substr(0, room)); + if (data.size() > room) + stop("truncated", "compiler diagnostic limit exceeded"); + return; + } + auto &line = channel == Channel::client ? control_line : event_line; + const std::size_t limit = channel == Channel::client ? 127 : 4095; + for (const auto c : data) { + if (channel == Channel::client && line.empty()) + control_origin = trace.stopped(); + if (c == '\n') { + if (channel == Channel::client) + control(line); + else + accept_event(); + line.clear(); + } else if (line.size() == limit) { + return stop("truncated", "line exceeds the channel limit"); + } else { + line.push_back(c); + } + if (!outcome.empty()) + return; + } + } + + void reap() { + if (status) + return; + auto waited = child.try_wait(); + if (!waited) + return stop("failed", "cannot wait for compiler"); + if (!*waited) + return; + status = **waited; + reaped_at = Clock::now(); + if (child.process_group_alive()) { + auto group = child.terminate(50ms); + if (!group || child.process_group_alive()) + stop("failed", "compiler descendants survived termination"); + } + } + + void check_deadlines() { + const auto now = Clock::now(); + if (interrupted) + return stop("cancelled", "session interrupted"); + if (command_deadline && now >= *command_deadline) + return stop("expired", "compiler failed to acknowledge the command"); + if (reaped_at && now - *reaped_at > 2s) + return stop("truncated", "compiler pipes remained open after exit"); + if (stopped_at && now - *stopped_at > 55s) + return stop("expired", "paused session expired"); + if (!stopped_at && running_time + now - running_since > 30s) + stop("expired", "running session expired"); + } + + std::expected run() { + while (outcome.empty() && (!status || events_open || diagnostics_open)) { + check_deadlines(); + if (!outcome.empty()) + break; + pollfd pipes[]{{controls_open ? STDIN_FILENO : -1, POLLIN, 0}, + {events_open ? child.stdout_fd() : -1, POLLIN, 0}, + {diagnostics_open ? child.stderr_fd() : -1, POLLIN, 0}}; + const int count = ::poll(pipes, 3, 25); + if (count < 0 && errno != EINTR) + stop("failed", "cannot poll compiler pipes"); + // Reject commands observed while running before accepting a new compiler stop. + for (unsigned i = 0; i < 3 && outcome.empty(); ++i) + if (count > 0 && pipes[i].revents != 0) + read_ready(static_cast(i), pipes[i].fd); + reap(); + } + if (!status || child.process_group_alive()) { + auto done = child.terminate(50ms); + if (!done) + return std::unexpected{"failed to reap the compiler process group"}; + status = *done; + } + const auto code = status->exited ? status->code : 128 + status->signal; + if (outcome.empty()) { + if (trace.terminal() == "cancelled" && code == 125) + outcome = "cancelled"; + else if (!saw_hello && code != 0) + outcome = "failed"; + else if (!trace.terminal().empty() || !trace.ended()) + outcome = "truncated"; + else + outcome = code == 0 ? "completed" : "failed"; + } + auto saved = trace.finish(outcome, code, diagnostics); + if (!saved) + return std::unexpected{saved.error()}; + if (!notice({{"kind", Json{std::string{"finished"}}}, {"outcome", Json{outcome}}, + {"exitCode", Json{static_cast(code)}}, {"reason", Json{error}}})) + return std::unexpected{"cannot deliver the final session status"}; + if (outcome == "completed") + return 0; + if (outcome == "cancelled") + return 125; + if (outcome == "expired") + return 124; + return outcome == "truncated" ? 126 : 1; + } +}; +} // namespace + +std::expected run_session(const RunOptions &options) { + if (options.compiler_sha256.size() != 64 || + options.compiler_sha256.find_first_not_of("0123456789abcdef") != std::string::npos) + return std::unexpected{"expected a lowercase SHA-256"}; + std::string source; + auto read = Void::LanguageServer::Detail::read_regular(options.source, source_limit, false, [&](auto part) { + source.append(reinterpret_cast(part.data()), part.size()); + return true; + }); + if (!read || !Protocol::serialize_json(Json{source})) + return std::unexpected{"input requires a stable UTF-8 source file within 256 KiB"}; + auto nonce = make_nonce(); + if (!nonce) + return std::unexpected{nonce.error()}; + auto directory = Void::FileSystem::TempDir::open("vls-gcc-session-"); + if (!directory) + return std::unexpected{"cannot create private compiler directory"}; + std::ofstream snapshot{directory->path() / "input.cpp", std::ios::binary}; + snapshot.write(source.data(), static_cast(source.size())); + snapshot.close(); + if (!snapshot) + return std::unexpected{"cannot write the compiler input"}; + if (::prctl(PR_SET_CHILD_SUBREAPER, 1) != 0) + return std::unexpected{"cannot supervise compiler descendants"}; + interrupted = 0; + std::signal(SIGTERM, interrupt); + std::signal(SIGINT, interrupt); + Void::Process::SpawnOptions launch; + launch.executable = "/proc/self/exe"; + launch.arguments = {"--leaf", options.compiler.string(), options.compiler_sha256, + *nonce, options.stepping ? "step" : "observe"}; + launch.working_directory = directory->path(); + launch.environment.mode = Void::Process::EnvMode::explicit_only; + launch.search_path = false; + launch.new_process_group = true; + launch.kill_grace = 50ms; + auto child = Void::Process::spawn(launch); + if (!child) + return std::unexpected{"cannot launch the private compiler worker"}; + auto trace = Trace::create(options.trace, source, options.compiler_sha256, *nonce, child->pid()); + if (!trace) + return std::unexpected{trace.error()}; + Nonblocking output{STDOUT_FILENO}, controls{child->stdin_fd()}; + if (!output.ok || !controls.ok) + return std::unexpected{"cannot set bounded session I/O"}; + Pump pump{*child, **trace, *nonce, options.stepping}; + return pump.run(); +} +} // namespace vls::gcc diff --git a/experiments/frontend/gcc-worker/Supervisor.hpp b/experiments/frontend/gcc-worker/Supervisor.hpp new file mode 100644 index 0000000..d810644 --- /dev/null +++ b/experiments/frontend/gcc-worker/Supervisor.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include +#include +#include + +namespace vls::gcc { + +struct RunOptions { + std::filesystem::path compiler; + std::string compiler_sha256; + std::filesystem::path source, trace; + bool stepping{}; +}; + +[[nodiscard]] std::expected run_session(const RunOptions &); + +} // namespace vls::gcc diff --git a/experiments/frontend/gcc-worker/Trace.cpp b/experiments/frontend/gcc-worker/Trace.cpp new file mode 100644 index 0000000..f24f945 --- /dev/null +++ b/experiments/frontend/gcc-worker/Trace.cpp @@ -0,0 +1,1300 @@ +#include "Trace.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::gcc { +namespace { + +using Protocol::as_array; +using Protocol::as_bool; +using Protocol::as_object; +using Protocol::as_string; +using Protocol::find_member; +using Protocol::Json; +using Void::System::OwnedFd; +using namespace std::string_view_literals; + +constexpr auto backend = "gcc-16.2.0/vls-eval-1"sv; +constexpr std::uint32_t max_events = 4096; +constexpr std::size_t max_event = 4096; // Includes the compiler's LF. +constexpr std::size_t max_trace = 1024 * 1024; +constexpr std::size_t max_source = 1024 * 1024; +constexpr std::size_t max_diagnostics = 1024 * 1024; +constexpr std::size_t max_metadata = 1024; +constexpr std::size_t max_command = 128; +constexpr std::size_t json_depth = 4; + +constexpr auto magic = "VLSTRC1\n"sv; +constexpr auto hex_digits = "0123456789abcdef"sv; +using Digest = std::array; +using RecordHeader = std::array; + +// One manifest, one finish, and at most one command per compiler event. +constexpr std::size_t max_journal_bytes = + magic.size() + max_source + max_diagnostics + 2 * (max_metadata + 1) + max_trace + + max_events * max_command + (2 + 2 * max_events) * (sizeof(RecordHeader) + sizeof(Digest)); + +enum class RecordType : char { manifest = 'M', event = 'E', command = 'C', finish = 'F' }; + +std::size_t payload_limit(RecordType type) { + switch (type) { + case RecordType::manifest: + return max_metadata + 1 + max_source; + case RecordType::event: + return max_event - 1; + case RecordType::command: + return max_command; + case RecordType::finish: + return max_metadata + 1 + max_diagnostics; + } + return 0; +} + +std::string io_error(std::string_view operation) { + const auto error = std::error_code(errno, std::generic_category()); + return std::string{operation} + ": " + error.message(); +} + +bool write_all(int fd, std::span bytes) { + while (!bytes.empty()) { + const auto count = ::write(fd, bytes.data(), bytes.size()); + if (count < 0 && errno == EINTR) { + continue; + } + if (count <= 0) { + if (count == 0) { + errno = EIO; + } + return false; + } + bytes = bytes.subspan(static_cast(count)); + } + return true; +} + +enum class ReadStatus { complete, short_read, error }; + +ReadStatus read_all(int fd, std::span bytes) { + while (!bytes.empty()) { + const auto count = ::read(fd, bytes.data(), bytes.size()); + if (count < 0 && errno == EINTR) { + continue; + } + if (count <= 0) { + return count == 0 ? ReadStatus::short_read : ReadStatus::error; + } + bytes = bytes.subspan(static_cast(count)); + } + return ReadStatus::complete; +} + +bool sync(int fd) { + int result; + do { + result = ::fsync(fd); + } while (result < 0 && errno == EINTR); + return result == 0; +} + +std::string hex(std::span bytes) { + std::string encoded; + encoded.reserve(bytes.size() * 2); + for (const auto byte : bytes) { + const auto value = std::to_integer(byte); + encoded.push_back(hex_digits[value >> 4u]); + encoded.push_back(hex_digits[value & 15u]); + } + return encoded; +} + +bool is_hex(std::string_view text, std::size_t size) { + return text.size() == size && + std::ranges::all_of(text, [](char ch) { return hex_digits.contains(ch); }); +} + +std::expected record_digest(const Digest &previous, const RecordHeader &header, + std::string_view payload) { + auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256); + if (!hasher || !hasher->update(std::as_bytes(std::span{previous})) || + !hasher->update(std::as_bytes(std::span{header})) || !hasher->update(payload)) { + return std::unexpected{"cannot hash trace record"}; + } + const auto hashed = hasher->finalize(); + Digest result; + if (!hashed || hashed->size() != result.size()) { + return std::unexpected{"cannot finalize trace record hash"}; + } + std::memcpy(result.data(), hashed->data(), result.size()); + return result; +} + +// Magic, then records of type, big-endian u32 length, digest, and exact payload bytes. +// The digest covers the previous digest (zero for the manifest), type/length, and payload. +class JournalWriter { + public: + explicit JournalWriter(OwnedFd fd) : fd_(std::move(fd)) {} + + TraceResult append(RecordType type, std::string_view payload) { + if (failed_) { + return std::unexpected{"trace journal is unavailable after a write failure"}; + } + if (payload.empty() || payload.size() > payload_limit(type)) { + return std::unexpected{"trace journal record is out of bounds"}; + } + const std::size_t size = payload.size(); + const RecordHeader header{static_cast(type), static_cast(size >> 24u), + static_cast(size >> 16u), static_cast(size >> 8u), + static_cast(size)}; + auto digest = record_digest(previous_, header, payload); + if (!digest) { + return std::unexpected{std::move(digest.error())}; + } + if (!write_all(fd_.get(), header) || !write_all(fd_.get(), *digest) || + !write_all(fd_.get(), payload) || !sync(fd_.get())) { + failed_ = true; + return std::unexpected{io_error("cannot append trace journal")}; + } + previous_ = *digest; + return {}; + } + + private: + OwnedFd fd_; + Digest previous_{}; + bool failed_{}; +}; + +bool valid_path(const std::filesystem::path &path) { + const auto name = path.filename(); + return !name.empty() && name != "." && name != ".." && !path.native().contains('\0'); +} + +std::expected create_journal(const std::filesystem::path &path, + std::string_view manifest) { + if (!valid_path(path)) { + return std::unexpected{"invalid trace journal path"}; + } + auto parent = path.parent_path(); + if (parent.empty()) { + parent = "."; + } + const OwnedFd directory{::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)}; + if (!directory) { + return std::unexpected{io_error("cannot open trace journal directory")}; + } + OwnedFd fd{::openat(directory.get(), path.filename().c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_APPEND | O_NOFOLLOW | O_CLOEXEC, 0600)}; + if (!fd) { + return std::unexpected{io_error("cannot exclusively create trace journal")}; + } + if (::fchmod(fd.get(), 0600) != 0 || !write_all(fd.get(), magic)) { + return std::unexpected{io_error("cannot initialize trace journal")}; + } + JournalWriter journal{std::move(fd)}; + if (auto result = journal.append(RecordType::manifest, manifest); !result) { + return std::unexpected{std::move(result.error())}; + } + if (!sync(directory.get())) { + return std::unexpected{io_error("cannot sync trace journal directory")}; + } + return journal; +} + +struct Record { + RecordType type; + std::string payload; +}; + +struct ReadFailure { + std::string message; + bool corrupt; +}; + +class JournalReader { + public: + JournalReader(int fd, std::uintmax_t bytes) : fd_(fd), remaining_(bytes) {} + + TraceResult read_magic() { + std::array actual{}; + if (auto result = take(actual); !result) { + return std::unexpected{std::move(result.error().message)}; + } + if (std::string_view{actual.data(), actual.size()} != magic) { + return std::unexpected{"incompatible trace journal header"}; + } + return {}; + } + + [[nodiscard]] bool has_remaining() const { return remaining_ != 0; } + + std::expected next() { + RecordHeader header; + if (auto result = take(header); !result) { + return std::unexpected{std::move(result.error())}; + } + const auto type = static_cast(header[0]); + std::uint32_t size = 0; + for (const auto byte : std::span{header}.subspan(1)) { + size = (size << 8u) | static_cast(byte); + } + if (size == 0 || size > payload_limit(type)) { + return std::unexpected{ + ReadFailure{"invalid trace journal record type or length", true}}; + } + Digest stored; + if (stored.size() + size > remaining_) { + return std::unexpected{ReadFailure{"truncated trace journal record", false}}; + } + if (auto result = take(stored); !result) { + return std::unexpected{std::move(result.error())}; + } + std::string payload(size, '\0'); + if (auto result = take(payload); !result) { + return std::unexpected{std::move(result.error())}; + } + auto actual = record_digest(previous_, header, payload); + if (!actual) { + return std::unexpected{ReadFailure{std::move(actual.error()), false}}; + } + if (*actual != stored) { + return std::unexpected{ReadFailure{"trace journal record hash mismatch", true}}; + } + previous_ = stored; + return Record{type, std::move(payload)}; + } + + private: + std::expected take(std::span bytes) { + if (bytes.size() > remaining_) { + return std::unexpected{ReadFailure{"truncated trace journal record", false}}; + } + if (bytes.size() > budget_) { + return std::unexpected{ReadFailure{"trace journal exceeds the v1 byte limit", true}}; + } + const auto status = read_all(fd_, bytes); + if (status != ReadStatus::complete) { + return std::unexpected{ReadFailure{status == ReadStatus::short_read + ? "truncated trace journal record" + : io_error("cannot read trace journal"), + false}}; + } + remaining_ -= bytes.size(); + budget_ -= bytes.size(); + return {}; + } + + int fd_; + std::uintmax_t remaining_; + std::size_t budget_ = max_journal_bytes; + Digest previous_{}; +}; + +std::string_view text(const Json::Object &object, std::string_view name) { + const auto *string = as_string(find_member(object, name)); + return string ? std::string_view{*string} : std::string_view{}; +} + +std::optional integer(const Json *field) { + // StrictJson preserves the distinction, even when a decimal rounds to an integer. + const auto *value = field ? std::get_if(&field->value) : nullptr; + return value ? std::optional{*value} : std::nullopt; +} + +std::optional ordinal(const Json::Object &object, std::string_view name) { + const auto number = integer(find_member(object, name)); + if (!number || !std::in_range(*number)) { + return std::nullopt; + } + return static_cast(*number); +} + +bool is_null(const Json *field) { + return field && std::holds_alternative(field->value); +} + +Json json_text(std::string_view value) { return Json{std::string{value}}; } + +Json nullable_ordinal(std::optional number) { + return number ? Json{static_cast(*number)} : Json{nullptr}; +} + +// The source and diagnostics are raw bytes in the journal. Preserve non-UTF-8 input in +// the JSON projection with an explicit alternate encoding. +void add_bytes(Json::Object &object, std::string_view name, std::string_view bytes) { + if (Void::Unicode::validate_utf8(bytes)) { + object.emplace(name, json_text(bytes)); + } else { + object.emplace(name, Json{nullptr}); + object.emplace(std::string{name} + "Hex", Json{hex(std::as_bytes(std::span{bytes}))}); + } +} + +struct Manifest { + std::string source; + std::string source_sha; + std::string compiler_sha; + std::string nonce; + std::int64_t pid; +}; + +std::expected source_hash(std::string_view source) { + const auto hashed = Void::Crypto::sha256(source); + if (!hashed) { + return std::unexpected{"cannot hash captured source"}; + } + return hex(*hashed); +} + +bool valid_identity(std::string_view compiler_sha, std::string_view nonce, std::int64_t pid) { + return pid > 0 && std::in_range(pid) && is_hex(nonce, 32) && is_hex(compiler_sha, 64); +} + +std::expected with_metadata(Json::Object fields, std::string_view bytes) { + auto encoded = Protocol::serialize_json(Json{std::move(fields)}, json_depth); + if (!encoded) { + return std::unexpected{std::move(encoded.error())}; + } + if (encoded->size() > max_metadata) { + return std::unexpected{"trace journal metadata is too large"}; + } + encoded->push_back('\n'); + encoded->append(bytes); + return encoded; +} + +std::expected, std::string> +split_metadata(std::string_view payload, std::size_t byte_limit) { + const auto separator = payload.substr(0, max_metadata + 1).find('\n'); + if (separator == std::string_view::npos || payload.size() - separator - 1 > byte_limit) { + return std::unexpected{"invalid trace journal metadata size"}; + } + auto parsed = Protocol::parse_json(payload.substr(0, separator), json_depth); + if (!parsed || !as_object(&*parsed)) { + return std::unexpected{"invalid trace journal metadata JSON"}; + } + return std::pair{std::get(std::move(parsed->value)), + payload.substr(separator + 1)}; +} + +std::expected read_manifest(std::string_view payload) { + auto split = split_metadata(payload, max_source); + if (!split) { + return std::unexpected{std::move(split.error())}; + } + const auto &[metadata, source] = *split; + const auto nonce = text(metadata, "nonce"); + const auto compiler_sha = text(metadata, "compilerSha256"); + const auto source_sha = text(metadata, "sourceSha256"); + const auto pid = integer(find_member(metadata, "pid")); + if (metadata.size() != 5 || text(metadata, "backend") != backend || !pid || + !valid_identity(compiler_sha, nonce, *pid) || !is_hex(source_sha, 64)) { + return std::unexpected{"invalid trace journal identity"}; + } + auto actual = source_hash(source); + if (!actual || *actual != source_sha) { + return std::unexpected{"captured trace source hash mismatch"}; + } + return Manifest{std::string{source}, std::move(*actual), std::string{compiler_sha}, + std::string{nonce}, *pid}; +} + +enum class Kind { + hello, + enter, + body, + value, + cached, + stopped, + resumed, + leave, + terminal, + frontend_end, + splice +}; + +constexpr std::array kind_names{"hello"sv, "enter"sv, "body"sv, "value"sv, + "cached"sv, "stopped"sv, "resumed"sv, "leave"sv, + "terminal"sv, "frontendEnd"sv, "splice"sv}; +// Recordings made before splice origins existed keep replaying unchanged. +constexpr std::array legacy_kind_names{"hello"sv, "enter"sv, "body"sv, "value"sv, + "cached"sv, "stopped"sv, "resumed"sv, "leave"sv, + "terminal"sv, "frontendEnd"sv}; +constexpr std::array target_kinds{"declaration"sv, "type"sv, "value"sv}; +constexpr std::array capabilities{"integralReturn"sv, "cooperativeStep"sv}; +constexpr std::array actions{"step"sv, "continue"sv, "cancel"sv}; +constexpr std::array leave_outcomes{"returned"sv, "failed"sv, "overflow"sv, "throw"sv, + "jump"sv, "void"sv, "constructor"sv}; +constexpr std::array terminal_reasons{"truncated"sv, "cancelled"sv, "controlTimeout"sv, + "controlEOF"sv, "controlError"sv, "controlLimit"sv}; +constexpr std::array process_outcomes{"completed"sv, "failed"sv, "cancelled"sv, "truncated"sv, + "expired"sv}; + +// Return the static spelling, so views retained in the state never reference parsed JSON. +std::string_view known(std::span options, std::string_view value) { + const auto found = std::ranges::find(options, value); + return found == options.end() ? std::string_view{} : *found; +} + +bool matches_set(const Json *value, std::span required) { + const auto *array = as_array(value); + return array && array->size() == required.size() && + std::ranges::all_of(required, [array](std::string_view name) { + return std::ranges::any_of(*array, [name](const Json &entry) { + const auto *string = as_string(&entry); + return string && *string == name; + }); + }); +} + +bool nullable_printable(const Json *value) { + const auto *string = as_string(value); + return is_null(value) || + (string && string->size() <= 512 && + std::ranges::all_of(*string, [](char ch) { return ch >= 32 && ch <= 126; })); +} + +bool positive_coordinate(const Json::Object &event, std::string_view name) { + const auto value = integer(find_member(event, name)); + return value && *value > 0 && std::in_range(*value); +} + +bool valid_value(const Json *value) { + const auto *object = as_object(value); + if (!object) { + return false; + } + const auto kind = text(*object, "kind"); + if (kind == "unavailable") { + return object->size() == 2 && text(*object, "reason") == "unsupportedScalar"; + } + const auto width = ordinal(*object, "precision"); + const auto bits = text(*object, "bitsHex"); + if (kind != "integer" || object->size() != 4 || !width || *width == 0 || *width > 64 || + !as_bool(find_member(*object, "signed")) || !is_hex(bits, (*width + 3) / 4)) { + return false; + } + const auto leading_bits = (*width - 1) % 4 + 1; + return hex_digits.find(bits.front()) < (1u << leading_bits); +} + +struct Frame { + enum class Phase { entered, body, cached }; + + std::uint32_t id; + std::optional parent; + Json::Object declaration; + Phase phase = Phase::entered; + std::optional value{}; + std::string_view outcome{}; + + Json inspect() const { + auto result = declaration; + if (phase == Phase::body) { + result.emplace("body", Json{true}); + } else if (phase == Phase::cached) { + result.emplace("cached", Json{true}); + } + if (!outcome.empty()) { + result.emplace("outcome", json_text(outcome)); + } + if (value) { + result.emplace("value", *value); + result.emplace("valueProvisional", Json{outcome != "returned"}); + } + return Json{std::move(result)}; + } +}; + +struct Completion { + std::string_view outcome; + int exit_code; + std::string diagnostics; +}; + +struct Capture { + Manifest manifest; + std::optional completion; + + ReplayMetadata metadata(bool ended, const ReadFailure *failure) const { + const bool partial = + failure || !completion || !ended || + (completion->outcome != "completed" && completion->outcome != "failed"); + return {backend, + manifest.nonce, + manifest.pid, + manifest.compiler_sha, + manifest.source_sha, + partial, + failure && failure->corrupt, + failure ? std::optional{failure->message} : std::nullopt, + completion ? std::optional{completion->outcome} : std::nullopt, + completion ? std::optional{completion->exit_code} : std::nullopt}; + } +}; + +void add_recording_status(Json::Object &cursor, const ReplayMetadata &metadata) { + cursor.emplace("partial", Json{metadata.partial}); + cursor.emplace("corrupt", Json{metadata.corrupt}); + if (metadata.journal_error) { + cursor.emplace("journalError", json_text(*metadata.journal_error)); + } + cursor.emplace("outcome", metadata.outcome ? json_text(*metadata.outcome) : Json{nullptr}); + cursor.emplace("exitCode", metadata.exit_code + ? Json{static_cast(*metadata.exit_code)} + : Json{nullptr}); +} + +struct SpliceOrigin { + std::string source; + std::uint32_t line{}, column{}; + std::string_view target_kind; + std::string target_name, target_source; + std::optional target_line, target_column; +}; + +struct CursorFields { + std::optional sequence; + std::optional stop; + std::string_view pending; + bool ended; + std::string_view terminal; + std::shared_ptr> origins; + + Json::Object inspect(const Manifest &manifest, Json::Array frames, Json last_leave) const { + Json::Object cursor{{"backend", json_text(backend)}, + {"nonce", json_text(manifest.nonce)}, + {"pid", Json{manifest.pid}}, + {"compilerSha256", json_text(manifest.compiler_sha)}, + {"sourceSha256", json_text(manifest.source_sha)}, + {"sequence", nullable_ordinal(sequence)}, + {"stop", nullable_ordinal(stop)}, + {"frames", Json{std::move(frames)}}, + {"lastLeave", std::move(last_leave)}, + {"pendingAction", pending.empty() ? Json{nullptr} : json_text(pending)}, + {"frontendEnded", Json{ended}}, + {"terminal", terminal.empty() ? Json{nullptr} : json_text(terminal)}}; + if (origins) { + Json::Array array; + for (const auto &origin : *origins) { + Json::Object fields{ + {"source", Json{origin.source}}, + {"line", Json{std::int64_t{origin.line}}}, + {"byteColumn", Json{std::int64_t{origin.column}}}, + {"targetKind", Json{std::string{origin.target_kind}}}, + {"targetName", origin.target_name.empty() ? Json{} : Json{origin.target_name}}, + {"targetSource", + origin.target_source.empty() ? Json{} : Json{origin.target_source}}}; + fields.emplace("targetLine", origin.target_line + ? Json{std::int64_t{*origin.target_line}} + : Json{}); + fields.emplace("targetByteColumn", origin.target_column + ? Json{std::int64_t{*origin.target_column}} + : Json{}); + array.push_back(Json{std::move(fields)}); + } + cursor.emplace("origins", Json{std::move(array)}); + } + return cursor; + } +}; + +// A child keeps the version of its parent observed on entry. Only the innermost frame +// can change, so saving a phase, value or leave costs one frame regardless of depth. +struct FrameVersion { + Json frame; + std::optional parent_version; +}; + +struct FrameRefs { + std::optional top; + std::optional last_leave; +}; + +struct IndexedCursor { + FrameRefs frames; + CursorFields fields; +}; + +struct RecordingIndex { + std::vector events; + std::vector cursors; + std::vector values; + std::vector versions; + + FrameRefs last_frames() const { return cursors.empty() ? FrameRefs{} : cursors.back().frames; } + + std::size_t save(const Frame &frame, std::optional parent) { + versions.push_back({frame.inspect(), parent}); + return versions.size() - 1; + } + + void record(ReplayEvent event, Kind kind, CursorFields fields, const Frame *top, + const std::optional &last_leave) { + auto refs = last_frames(); + switch (kind) { + case Kind::enter: + refs.top = save(*top, refs.top); + break; + case Kind::value: + if (text(*as_object(&*top->value), "kind") == "integer") { + values.push_back({event.sequence, std::nullopt}); + } + [[fallthrough]]; + case Kind::body: + case Kind::cached: + refs.top = save(*top, versions[*refs.top].parent_version); + break; + case Kind::leave: { + const auto parent = versions[*refs.top].parent_version; + refs.last_leave = save(*last_leave, parent); + refs.top = parent; + break; + } + case Kind::stopped: + // Timeline requires an immediately preceding integer value on this same frame. + values.back().stop_sequence = event.sequence; + break; + default: + break; + } + events.push_back(event); + cursors.push_back({refs, fields}); + } + + Json inspect(const Manifest &manifest, const IndexedCursor &cursor) const { + Json::Array frames; + for (auto top = cursor.frames.top; top; top = versions[*top].parent_version) { + frames.push_back(versions[*top].frame); + } + std::ranges::reverse(frames); + const auto leave = cursor.frames.last_leave; + return Json{cursor.fields.inspect(manifest, std::move(frames), + leave ? versions[*leave].frame : Json{nullptr})}; + } +}; + +class Timeline { + public: + explicit Timeline(Manifest manifest) : capture_{std::move(manifest), std::nullopt} { + // Append a verified event before making its change visible. Frame pushes then need no + // allocation once a complete journal record has been committed. + frames_.reserve(max_events); + } + + TraceResult event(std::string_view line, JournalWriter *journal = nullptr, + RecordingIndex *index = nullptr) { + if (sequence_ == max_events || line.size() >= max_event || line.contains('\n') || + line.size() + 1 > max_trace - trace_bytes_) { + return std::unexpected{"compiler trace event or stream exceeds wire bounds"}; + } + auto parsed = Protocol::parse_json(line, json_depth); + const auto *event = parsed ? as_object(&*parsed) : nullptr; + if (!event || integer(find_member(*event, "v")) != 1 || + text(*event, "nonce") != capture_.manifest.nonce || + ordinal(*event, "seq") != sequence_) { + return std::unexpected{"invalid compiler trace envelope"}; + } + const auto name = std::ranges::find(kind_names, text(*event, "kind")); + if (name == kind_names.end()) { + return std::unexpected{"unknown compiler trace event kind"}; + } + const auto kind = static_cast(name - kind_names.begin()); + if (auto result = validate(*event, kind); !result) { + return result; + } + if (journal) { + if (auto result = journal->append(RecordType::event, line); !result) { + return result; + } + } + ReplayEvent summary{}; + if (index) { + summary = { + sequence_, *name, ordinal(*event, "frame"), ordinal(*event, "parent"), + std::nullopt, std::nullopt}; + if (kind == Kind::resumed) { + // validate_frame matched both echoed fields to this authorization. + summary.acknowledged_stop = stop_; + summary.acknowledged_action = pending_; + } + } + apply(std::get(std::move(parsed->value)), kind); + trace_bytes_ += line.size() + 1; + ++sequence_; + if (kind != Kind::splice) { + last_kind_ = kind; + } + if (index) { + index->record(summary, kind, cursor_fields(), + frames_.empty() ? nullptr : &frames_.back(), last_leave_); + } + return {}; + } + + TraceResult authorize(std::uint32_t stop, std::string_view requested, + JournalWriter *journal = nullptr) { + const auto action = known(actions, requested); + if (!stopped() || stopped() != stop || action.empty()) { + return std::unexpected{ + "trace command needs the current unconsumed stop and a supported action"}; + } + if (journal) { + auto encoded = Protocol::serialize_json( + Json{Json::Object{{"action", json_text(action)}, {"stop", nullable_ordinal(stop)}}}, + json_depth); + if (!encoded) { + return std::unexpected{std::move(encoded.error())}; + } + if (auto result = journal->append(RecordType::command, *encoded); !result) { + return result; + } + } + // One command per verified stop bounds the command count by the event count. + pending_ = action; + return {}; + } + + TraceResult finish(std::string_view requested, int code, std::string_view diagnostics, + JournalWriter *journal = nullptr) { + const auto outcome = known(process_outcomes, requested); + if (capture_.completion || outcome.empty() || diagnostics.size() > max_diagnostics || + (outcome == "completed" && (!ended_ || code != 0))) { + return std::unexpected{"invalid trace process outcome"}; + } + Completion completion{outcome, code, std::string{diagnostics}}; + if (journal) { + auto encoded = with_metadata({{"outcome", json_text(outcome)}, + {"exitCode", Json{static_cast(code)}}}, + completion.diagnostics); + if (!encoded) { + return std::unexpected{std::move(encoded.error())}; + } + if (auto result = journal->append(RecordType::finish, *encoded); !result) { + return result; + } + } + capture_.completion = std::move(completion); + return {}; + } + + std::optional sequence() const { + return sequence_ == 0 ? std::nullopt : std::optional{sequence_ - 1}; + } + + std::optional stopped() const { + return pending_.empty() && !capture_.completion ? stop_ : std::nullopt; + } + + bool ended() const { return ended_; } + std::string_view terminal() const { return terminal_; } + + CursorFields cursor_fields() const { + return {sequence(), stopped(), pending_, ended_, terminal_, origins_}; + } + + Capture release_capture() && { return std::move(capture_); } + + Json inspection() const { + Json::Array frames; + frames.reserve(frames_.size()); + for (const auto &frame : frames_) { + frames.push_back(frame.inspect()); + } + auto cursor = cursor_fields().inspect(capture_.manifest, std::move(frames), + last_leave_ ? last_leave_->inspect() : Json{nullptr}); + add_recording_status(cursor, capture_.metadata(ended_, nullptr)); + return Json{std::move(cursor)}; + } + + private: + static constexpr std::size_t envelope_fields = 4; + static constexpr std::size_t frame_fields = envelope_fields + 2; + + TraceResult validate(const Json::Object &event, Kind kind) const { + if (capture_.completion || ended_ || !terminal_.empty()) { + return std::unexpected{"compiler trace event after termination"}; + } + if (sequence_ == 0) { + if (kind == Kind::hello && event.size() == envelope_fields + 4 && + text(event, "backend") == backend && + integer(find_member(event, "pid")) == capture_.manifest.pid && + matches_set(find_member(event, "capabilities"), capabilities) && + (matches_set(find_member(event, "kinds"), kind_names) || + matches_set(find_member(event, "kinds"), legacy_kind_names))) { + return {}; + } + return std::unexpected{"invalid GCC evaluator handshake"}; + } + if (stop_ && kind != Kind::resumed && kind != Kind::terminal) { + return std::unexpected{"compiler moved without acknowledging the stopped command"}; + } + switch (kind) { + case Kind::hello: + return std::unexpected{"duplicate GCC evaluator handshake"}; + case Kind::terminal: { + const auto reason = known(terminal_reasons, text(event, "reason")); + if (reason == "truncated" && event.size() == envelope_fields + 1) { + return {}; + } + if (!reason.empty() && reason != "truncated" && event.size() == envelope_fields + 2 && + stop_ && ordinal(event, "stop") == stop_ && + (reason != "cancelled" || pending_ == "cancel")) { + return {}; + } + return std::unexpected{"invalid compiler terminal event"}; + } + case Kind::frontend_end: + if (event.size() == envelope_fields && frames_.empty()) { + return {}; + } + return std::unexpected{"frontendEnd requires a balanced trace"}; + case Kind::splice: { + if (!declared_splice_) { + return std::unexpected{"splice origin was not declared in the handshake"}; + } + const auto target_kind = known(target_kinds, text(event, "targetKind")); + const bool coordinates = (is_null(find_member(event, "targetLine")) && + is_null(find_member(event, "targetByteColumn"))) || + (positive_coordinate(event, "targetLine") && + positive_coordinate(event, "targetByteColumn")); + if (event.size() == envelope_fields + 8 && !target_kind.empty() && + nullable_printable(find_member(event, "source")) && + positive_coordinate(event, "line") && positive_coordinate(event, "byteColumn") && + nullable_printable(find_member(event, "targetName")) && + nullable_printable(find_member(event, "targetSource")) && coordinates) { + return {}; + } + return std::unexpected{"invalid compiler splice origin"}; + } + default: + return validate_frame(event, kind); + } + } + + TraceResult validate_frame(const Json::Object &event, Kind kind) const { + const auto *top = frames_.empty() ? nullptr : &frames_.back(); + const auto id = ordinal(event, "frame"); + const auto parent = kind == Kind::enter ? (top ? std::optional{top->id} : std::nullopt) + : (top ? top->parent : std::nullopt); + const bool parent_matches = + parent ? ordinal(event, "parent") == parent : is_null(find_member(event, "parent")); + if (!id || !parent_matches || + (kind == Kind::enter ? *id != sequence_ : !top || *id != top->id)) { + return std::unexpected{"invalid compiler trace frame or parent"}; + } + switch (kind) { + case Kind::enter: { + const auto location = text(event, "sourceKind"); + const bool located = + location == "logicalDeclaration" && event.size() == frame_fields + 5 && + nullable_printable(find_member(event, "source")) && + positive_coordinate(event, "line") && positive_coordinate(event, "byteColumn"); + if (nullable_printable(find_member(event, "name")) && + (located || (location == "unavailable" && event.size() == frame_fields + 2))) { + return {}; + } + break; + } + case Kind::body: + case Kind::cached: + if (event.size() == frame_fields && top->phase == Frame::Phase::entered) { + return {}; + } + break; + case Kind::value: + if (event.size() == frame_fields + 1 && top->phase == Frame::Phase::body && + !top->value && valid_value(find_member(event, "value"))) { + return {}; + } + break; + case Kind::stopped: + if (event.size() == frame_fields && !disarmed_ && last_kind_ == Kind::value && + top->value && text(*as_object(&*top->value), "kind") == "integer") { + return {}; + } + break; + case Kind::resumed: + if (event.size() == frame_fields + 2 && stop_ && ordinal(event, "stop") == stop_ && + (pending_ == "step" || pending_ == "continue") && + text(event, "action") == pending_) { + return {}; + } + break; + case Kind::leave: + if (event.size() == frame_fields + 1 && + !known(leave_outcomes, text(event, "outcome")).empty()) { + return {}; + } + break; + default: + break; + } + return std::unexpected{"invalid compiler trace frame event"}; + } + + void apply(Json::Object event, Kind kind) { + switch (kind) { + case Kind::hello: + declared_splice_ = matches_set(find_member(event, "kinds"), kind_names); + break; + case Kind::enter: { + const auto parent = ordinal(event, "parent"); + event.erase("v"); + event.erase("seq"); + event.erase("nonce"); + event.erase("kind"); + frames_.push_back( + Frame{.id = sequence_, .parent = parent, .declaration = std::move(event)}); + break; + } + case Kind::body: + frames_.back().phase = Frame::Phase::body; + break; + case Kind::cached: + frames_.back().phase = Frame::Phase::cached; + break; + case Kind::value: + frames_.back().value = std::move(event.find("value")->second); + break; + case Kind::stopped: + stop_ = sequence_; + break; + case Kind::resumed: + disarmed_ = pending_ == "continue"; + pending_ = {}; + stop_.reset(); + break; + case Kind::leave: + frames_.back().outcome = known(leave_outcomes, text(event, "outcome")); + last_leave_ = std::move(frames_.back()); + frames_.pop_back(); + break; + case Kind::terminal: + terminal_ = known(terminal_reasons, text(event, "reason")); + pending_ = {}; + stop_.reset(); + break; + case Kind::frontend_end: + ended_ = true; + break; + case Kind::splice: { + auto next = origins_ ? std::make_shared>(*origins_) + : std::make_shared>(); + if (next->size() < max_splice_origins) { + SpliceOrigin origin; + origin.source = text(event, "source"); + origin.line = static_cast(*ordinal(event, "line")); + origin.column = static_cast(*ordinal(event, "byteColumn")); + origin.target_kind = known(target_kinds, text(event, "targetKind")); + origin.target_name = text(event, "targetName"); + origin.target_source = text(event, "targetSource"); + origin.target_line = ordinal(event, "targetLine"); + origin.target_column = ordinal(event, "targetByteColumn"); + next->push_back(std::move(origin)); + } + origins_ = std::move(next); + break; + } + } + } + + Capture capture_; + std::vector frames_; + std::optional last_leave_; + std::optional stop_; + std::string_view pending_; + std::string_view terminal_; + std::size_t trace_bytes_{}; + std::uint32_t sequence_{}; + static constexpr std::size_t max_splice_origins = 256; + std::shared_ptr> origins_; + bool declared_splice_{}; + Kind last_kind_ = Kind::hello; + bool disarmed_{}; + bool ended_{}; +}; + +TraceResult apply_record(Timeline &timeline, const Record &record, RecordingIndex &index) { + switch (record.type) { + case RecordType::event: + return timeline.event(record.payload, nullptr, &index); + case RecordType::command: { + auto parsed = Protocol::parse_json(record.payload, json_depth); + const auto *command = parsed ? as_object(&*parsed) : nullptr; + if (!command || command->size() != 2) { + return std::unexpected{"invalid trace command record"}; + } + const auto stop = ordinal(*command, "stop"); + if (!stop) { + return std::unexpected{"invalid recorded trace stop"}; + } + return timeline.authorize(*stop, text(*command, "action")); + } + case RecordType::finish: { + auto split = split_metadata(record.payload, max_diagnostics); + if (!split) { + return std::unexpected{std::move(split.error())}; + } + const auto &[metadata, diagnostics] = *split; + const auto exit_code = integer(find_member(metadata, "exitCode")); + if (metadata.size() != 2 || !exit_code || !std::in_range(*exit_code)) { + return std::unexpected{"invalid trace exit record"}; + } + return timeline.finish(text(metadata, "outcome"), static_cast(*exit_code), + diagnostics); + } + case RecordType::manifest: + return std::unexpected{"duplicate trace journal manifest"}; + } + return std::unexpected{"unknown trace journal record"}; +} + +} // namespace + +struct Trace::State { + State(Manifest manifest, JournalWriter writer) + : timeline(std::move(manifest)), journal(std::move(writer)) {} + + std::mutex mutex; + Timeline timeline; + JournalWriter journal; +}; + +Trace::Trace(std::unique_ptr state) : state_(std::move(state)) {} +Trace::~Trace() = default; + +std::expected, std::string> +Trace::create(const std::filesystem::path &output, std::string_view source, + std::string_view compiler_sha, std::string_view nonce, std::int64_t pid) { + if (source.size() > max_source || !valid_identity(compiler_sha, nonce, pid)) { + return std::unexpected{"invalid trace creation identity or source size"}; + } + auto hash = source_hash(source); + if (!hash) { + return std::unexpected{std::move(hash.error())}; + } + auto payload = with_metadata({{"backend", json_text(backend)}, + {"compilerSha256", json_text(compiler_sha)}, + {"nonce", json_text(nonce)}, + {"pid", Json{pid}}, + {"sourceSha256", Json{*hash}}}, + source); + if (!payload) { + return std::unexpected{std::move(payload.error())}; + } + auto journal = create_journal(output, *payload); + if (!journal) { + return std::unexpected{std::move(journal.error())}; + } + Manifest manifest{std::string{source}, std::move(*hash), std::string{compiler_sha}, + std::string{nonce}, pid}; + return std::unique_ptr{ + new Trace{std::make_unique(std::move(manifest), std::move(*journal))}}; +} + +TraceResult Trace::event(std::string_view line) { + const std::scoped_lock lock(state_->mutex); + return state_->timeline.event(line, &state_->journal); +} + +TraceResult Trace::authorize(std::uint32_t stop, std::string_view action) { + const std::scoped_lock lock(state_->mutex); + return state_->timeline.authorize(stop, action, &state_->journal); +} + +std::optional Trace::stopped() const { + const std::scoped_lock lock(state_->mutex); + return state_->timeline.stopped(); +} + +bool Trace::ended() const { + const std::scoped_lock lock(state_->mutex); + return state_->timeline.ended(); +} + +std::string_view Trace::terminal() const { + const std::scoped_lock lock(state_->mutex); + return state_->timeline.terminal(); +} + +Json Trace::inspection() const { + const std::scoped_lock lock(state_->mutex); + return state_->timeline.inspection(); +} + +TraceResult Trace::finish(std::string_view outcome, int code, std::string_view diagnostics) { + const std::scoped_lock lock(state_->mutex); + return state_->timeline.finish(outcome, code, diagnostics, &state_->journal); +} + +struct ReplayRecording::State { + Capture capture; + RecordingIndex index; + CursorFields final_fields; + std::optional failure; +}; + +ReplayRecording::ReplayRecording(std::unique_ptr state) : state_(std::move(state)) {} +ReplayRecording::~ReplayRecording() = default; + +std::expected, std::string> +ReplayRecording::open(const std::filesystem::path &path) { + if (!path.is_absolute() || !valid_path(path)) { + return std::unexpected{"trace recording requires an absolute journal file path"}; + } + const OwnedFd file{ + ::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_NOCTTY | O_CLOEXEC)}; + if (!file) { + return std::unexpected{io_error("cannot open trace journal")}; + } + struct stat status{}; + if (::fstat(file.get(), &status) != 0 || !S_ISREG(status.st_mode) || status.st_size < 0) { + return std::unexpected{"trace replay requires a regular file"}; + } + // Observe a fixed file-length prefix even if a live writer appends while replay runs. + JournalReader reader{file.get(), static_cast(status.st_size)}; + if (auto header = reader.read_magic(); !header) { + return std::unexpected{std::move(header.error())}; + } + auto first = reader.next(); + if (!first) { + return std::unexpected{std::move(first.error().message)}; + } + if (first->type != RecordType::manifest) { + return std::unexpected{"trace journal does not begin with a manifest"}; + } + auto manifest = read_manifest(first->payload); + if (!manifest) { + return std::unexpected{std::move(manifest.error())}; + } + Timeline timeline{std::move(*manifest)}; + RecordingIndex index; + std::optional failure; + while (reader.has_remaining()) { + auto record = reader.next(); + if (!record) { + failure = std::move(record.error()); + break; + } + if (record->type == RecordType::finish && reader.has_remaining()) { + failure = ReadFailure{"trace journal has data after its process outcome", true}; + break; + } + if (auto applied = apply_record(timeline, *record, index); !applied) { + failure = ReadFailure{std::move(applied.error()), true}; + break; + } + } + const auto final_fields = timeline.cursor_fields(); + auto state = std::make_unique(std::move(timeline).release_capture(), std::move(index), + final_fields, std::move(failure)); + return std::shared_ptr{new ReplayRecording{std::move(state)}}; +} + +ReplayMetadata ReplayRecording::metadata() const { + return state_->capture.metadata(state_->final_fields.ended, + state_->failure ? &*state_->failure : nullptr); +} + +std::string_view ReplayRecording::source_bytes() const { return state_->capture.manifest.source; } + +std::optional ReplayRecording::diagnostic_bytes() const { + const auto &completion = state_->capture.completion; + return completion ? std::optional{completion->diagnostics} : std::nullopt; +} + +std::size_t ReplayRecording::event_count() const { return state_->index.events.size(); } + +std::expected, std::string> +ReplayRecording::event_page(std::size_t offset, std::size_t count) const { + if (offset > event_count() || count > max_page_size) { + return std::unexpected{"requested event page is out of bounds"}; + } + return std::span{state_->index.events}.subspan(offset, std::min(count, event_count() - offset)); +} + +std::expected, std::string> +ReplayRecording::next_value(std::optional after) const { + const auto &points = state_->index.values; + if (after && *after >= event_count()) { + return std::unexpected{"requested event is outside the verified trace prefix"}; + } + const auto next = + after ? std::ranges::upper_bound(points, *after, {}, &ReplayValuePoint::value_sequence) + : points.begin(); + return next == points.end() ? std::nullopt : std::optional{*next}; +} + +std::expected, std::string> +ReplayRecording::previous_value(std::optional before) const { + const auto &points = state_->index.values; + if (before && *before >= event_count()) { + return std::unexpected{"requested event is outside the verified trace prefix"}; + } + const auto end_of_point = [](const ReplayValuePoint &point) { + return point.stop_sequence.value_or(point.value_sequence); + }; + const auto limit = + before ? std::ranges::lower_bound(points, *before, {}, end_of_point) : points.end(); + return limit == points.begin() ? std::nullopt : std::optional{*std::prev(limit)}; +} + +std::expected ReplayRecording::cursor_at(std::uint32_t sequence) const { + if (sequence >= event_count()) { + return std::unexpected{"requested event is outside the verified trace prefix"}; + } + return state_->index.inspect(state_->capture.manifest, state_->index.cursors[sequence]); +} + +Json ReplayRecording::final_cursor() const { + return state_->index.inspect(state_->capture.manifest, + {state_->index.last_frames(), state_->final_fields}); +} + +std::expected replay(const std::filesystem::path &path, + std::optional sequence) { + if (!valid_path(path) || (sequence && *sequence >= max_events)) { + return std::unexpected{"invalid trace replay path or event sequence"}; + } + std::error_code error; + const auto absolute = std::filesystem::absolute(path, error); + if (error) { + return std::unexpected{error.message()}; + } + auto opened = ReplayRecording::open(absolute); + if (!opened) { + return std::unexpected{std::move(opened.error())}; + } + const auto &recording = **opened; + auto cursor = sequence ? recording.cursor_at(*sequence) + : std::expected{recording.final_cursor()}; + if (!cursor) { + return cursor; + } + auto &fields = std::get(cursor->value); + add_recording_status(fields, recording.metadata()); + add_bytes(fields, "source", recording.source_bytes()); + if (auto diagnostics = recording.diagnostic_bytes()) { + add_bytes(fields, "diagnostics", *diagnostics); + } else { + fields.emplace("diagnostics", Json{nullptr}); + } + return cursor; +} + +} // namespace vls::gcc diff --git a/experiments/frontend/gcc-worker/Trace.hpp b/experiments/frontend/gcc-worker/Trace.hpp new file mode 100644 index 0000000..4844e96 --- /dev/null +++ b/experiments/frontend/gcc-worker/Trace.hpp @@ -0,0 +1,112 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::gcc { + +namespace Protocol = Void::LanguageServer::Protocol; +using TraceResult = std::expected; + +// The journal is exclusively created and binds the immutable input to this invocation. +// Commands are journalled before dispatch. Acknowledgement is a separate compiler event. +class Trace { + public: + static std::expected, std::string> + create(const std::filesystem::path &output, std::string_view source, + std::string_view compiler_sha, std::string_view nonce, std::int64_t pid); + ~Trace(); + [[nodiscard]] TraceResult event(std::string_view line); + [[nodiscard]] TraceResult authorize(std::uint32_t stop, std::string_view action); + [[nodiscard]] std::optional stopped() const; + [[nodiscard]] bool ended() const; + [[nodiscard]] std::string_view terminal() const; + [[nodiscard]] Protocol::Json inspection() const; + [[nodiscard]] TraceResult finish(std::string_view outcome, int exit_code, + std::string_view diagnostics); + + private: + struct State; + explicit Trace(std::unique_ptr); + std::unique_ptr state_; +}; + +struct ReplayEvent { + std::uint32_t sequence; + std::string_view kind; + std::optional frame; + std::optional parent; + // Present together on a compiler resumed event. + std::optional acknowledged_stop; + std::optional acknowledged_action; +}; + +struct ReplayValuePoint { + std::uint32_t value_sequence; + std::optional stop_sequence; +}; + +struct ReplayMetadata { + std::string_view backend; + std::string_view nonce; + std::int64_t pid; + std::string_view compiler_sha256; + std::string_view source_sha256; + bool partial; + bool corrupt; + std::optional journal_error; + std::optional outcome; + std::optional exit_code; +}; + +// Views borrow this recording. A shared owner keeps its validated prefix and raw bytes alive. +class ReplayRecording { + public: + static std::expected, std::string> + open(const std::filesystem::path &absolute_path); + ~ReplayRecording(); + + [[nodiscard]] ReplayMetadata metadata() const; + [[nodiscard]] std::string_view source_bytes() const; + [[nodiscard]] std::optional diagnostic_bytes() const; + [[nodiscard]] std::size_t event_count() const; + + // Zero-based offset; offset == event_count() is an empty page. Larger offsets or + // requests above max_page_size return an error. The span is an O(1) immutable slice. + static constexpr std::size_t max_page_size = 256; + [[nodiscard]] std::expected, std::string> + event_page(std::size_t offset, std::size_t count) const; + + // Strictly beyond the entire value/optional-stop pair. Omit the anchor for first/last. + // A boundary returns an empty optional; a sequence outside the verified prefix is an error. + [[nodiscard]] std::expected, std::string> + next_value(std::optional after = {}) const; + [[nodiscard]] std::expected, std::string> + previous_value(std::optional before = {}) const; + + // Owned JSON uses Trace's frame schema. Historical state is immediately after the event. + // final_cursor also sees subsequent command authorization and final stop consumption. + // Each query copies only its active frames, last leave and identity, at most 4096 events deep. + [[nodiscard]] std::expected + cursor_at(std::uint32_t sequence) const; + [[nodiscard]] Protocol::Json final_cursor() const; + + private: + struct State; + explicit ReplayRecording(std::unique_ptr); + std::unique_ptr state_; +}; + +[[nodiscard]] std::expected +replay(const std::filesystem::path &journal, std::optional sequence); + +} // namespace vls::gcc diff --git a/include/Void/LanguageServer/Build/Model.hpp b/include/Void/LanguageServer/Build/Model.hpp new file mode 100644 index 0000000..74d51fe --- /dev/null +++ b/include/Void/LanguageServer/Build/Model.hpp @@ -0,0 +1,331 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Build { + +struct WorkspaceIdentity { + std::filesystem::path root; + std::string session; + bool operator==(const WorkspaceIdentity &) const = default; +}; + +struct GenerationIdentity { + WorkspaceIdentity workspace; + std::string provider, revision; +}; + +enum class ContextRole { unknown, target, host_description }; + +// The alternative is stable across record reorderings. Providers distinguish commands using +// structured values or collision-checked identities. An empty TU is reserved for an original +// provider record whose physical owner could not be established. +struct ContextKey { + std::optional profile, target; + ContextRole role{ContextRole::unknown}; + std::string alternative; + std::filesystem::path owning_tu; + auto operator<=>(const ContextKey &) const = default; +}; + +enum class SourceOrigin { unknown, workspace, snapshot, generated, external }; +enum class Editability { unknown, read_only, editable }; +struct SourceMapping { + std::filesystem::path source_path; + std::optional compiler_path; + SourceOrigin origin{SourceOrigin::unknown}; + Editability editability{Editability::unknown}; + std::optional provenance; +}; + +struct OriginalCommand { + std::filesystem::path metadata_file; + std::string record_id; + std::optional> arguments; + std::optional command; + std::optional original_record; +}; + +enum class Availability { unknown, missing, stale, ready }; +struct Prerequisite { + std::string name; + std::optional input_identity; + Availability state{Availability::unknown}; +}; +struct Artifact { + std::filesystem::path path; + std::optional content_identity; + Availability state{Availability::unknown}; +}; + +// A provider keeps the generation's immutable artifact contents available for this lifetime. +class ArtifactLease { + public: + virtual ~ArtifactLease() = default; +}; + +struct BuildContext { + ContextKey key; + std::optional source_language; + std::optional original; + std::optional> semantic_arguments; + std::optional working_directory; + std::optional toolchain, standard_library, environment; + // One mapping per known source including the owning TU. A header may occur in many contexts. + std::vector sources; + // An engaged empty list is a verified absence of requirements. + std::optional> prerequisites; + std::optional> artifacts; + std::vector limitations; + + [[nodiscard]] const SourceMapping *mapping_for(const std::filesystem::path &source) const; +}; + +enum class ModelError { + invalid_identity, + invalid_context, + duplicate_context, + invalid_mapping, + wrong_scope, + invalid_input, + superseded, + sequence_exhausted, + no_inputs, + operation_unavailable +}; + +class BuildGeneration; +using Generation = std::shared_ptr; +class BuildGeneration { + public: + // Providers supply normalized, absolute physical source paths. Freeze the metadata into + // generation-owned storage, including argv, mappings and original provider records. + [[nodiscard]] static std::expected + create(const GenerationIdentity &identity, const std::vector &records, + std::shared_ptr lease = {}); + BuildGeneration(const BuildGeneration &) = delete; + BuildGeneration &operator=(const BuildGeneration &) = delete; + [[nodiscard]] const GenerationIdentity &identity() const { return identity_; } + [[nodiscard]] const std::vector &contexts() const { return records_; } + [[nodiscard]] std::span + candidates(const std::filesystem::path &source) const; + [[nodiscard]] const BuildContext *find(const ContextKey &key) const; + [[nodiscard]] bool retains_artifacts() const { return static_cast(lease_); } + + private: + BuildGeneration(GenerationIdentity, std::vector, + std::shared_ptr); + GenerationIdentity identity_; + std::vector records_; + std::shared_ptr lease_; + std::map> by_source_; +}; + +// Persist the per-file value in the configuration owner. Lookups never edit that configuration. +struct FileOverride { + std::filesystem::path workspace_root, file; + std::string provider; + ContextKey key; + bool operator==(const FileOverride &) const = default; +}; +struct EditorSelection { + std::filesystem::path workspace_root; + std::string provider; + std::optional profile, target, alternative; + std::optional role; + bool operator==(const EditorSelection &) const = default; +}; +enum class SelectionReason { file_override, missing_override, editor, fallback, no_owner }; + +struct SelectionScope { + WorkspaceIdentity workspace; + std::filesystem::path file; +}; + +class ContextSelection { + public: + const std::shared_ptr scope; + const Generation generation; + const std::uint64_t revision; + const std::optional file_override; + const std::optional editor; + const SelectionReason reason; + const BuildContext *const selected; + [[nodiscard]] auto alternatives() const { return generation->candidates(scope->file); } + + private: + friend class SelectionState; + ContextSelection(std::shared_ptr, Generation, std::uint64_t, + std::optional, std::optional, SelectionReason, + const BuildContext *); +}; +using Selection = std::shared_ptr; + +// One sequenced owner per session/workspace/document. Update on each real selection transition. +// Fallback, including ties within the editor's profile/target, uses ascending ContextKey order. +class SelectionState { + public: + SelectionState(const WorkspaceIdentity &workspace, const std::filesystem::path &file); + SelectionState(const SelectionState &) = delete; + SelectionState &operator=(const SelectionState &) = delete; + [[nodiscard]] std::expected + update(Generation generation, const std::optional &file_override = {}, + const std::optional &editor = {}); + [[nodiscard]] const auto &scope() const { return scope_; } + + private: + std::shared_ptr scope_; + Selection current_; +}; + +using Snapshot = std::shared_ptr; +enum class DependencyKind { include, import, generated_source, response_file }; +struct DependencyInput { + DependencyKind kind; + std::string name; + std::filesystem::path lookup_path; + Snapshot source; +}; +struct BackendIdentity { + std::string implementation, version, protocol; + bool operator==(const BackendIdentity &) const = default; +}; + +struct ContextProof { + Generation generation; + ContextKey key; + // Identity of the checked disposition, including that context's TU, dependencies and + // authority. The rename owner also supplies proofs for candidates it ruled unaffected. + std::optional verification; + bool operator==(const ContextProof &) const = default; +}; +struct RenameCoverage { + // The rename owner certifies the complete declared root set and affected-context census. + // The census includes every alternative for the requested file and can span other files. + std::vector workspace_roots; + std::optional> contexts; + std::optional editable_spelling_proof; + bool operator==(const RenameCoverage &) const = default; +}; +struct AnalysisInputs { + Snapshot document, translation_unit; + std::optional> dependencies; + // The owner advances this on any change affecting ordered include/import lookup, including + // misses and overlay changes, across ALL search roots. Absent means coverage is unknown. + std::optional lookup_epoch; + // Session owners provide monotonic configuration and workspace authority identities. + // A dispatcher separately checks permission for its exact invocation. + std::optional configuration_generation, trust_generation; + std::optional backend; + std::optional rename; +}; + +enum class Operation { status, diagnostics, semantic, rename }; +enum class ReadinessLevel { unavailable, degraded, ready }; +enum class InputIssue { + context, + document, + translation_unit, + language, + command, + working_directory, + backend, + configuration, + trust, + command_provenance, + source_mapping, + toolchain, + standard_library, + environment, + prerequisites, + artifacts, + provider_limitation, + dependencies, + lookup_coverage, + affected_contexts, + edit_provenance +}; +struct Readiness { + ReadinessLevel level; + std::vector issues; +}; + +class AnalysisRevision; +using Revision = std::shared_ptr; +class AnalysisRevision { + public: + // Copy metadata once and retain immutable snapshots from the session document store. + [[nodiscard]] static std::expected capture(Selection, + const AnalysisInputs &); + [[nodiscard]] const Readiness &readiness(Operation op) const; + [[nodiscard]] bool same_input_as(const AnalysisRevision &) const; + const Selection selection; + const AnalysisInputs inputs; + + private: + AnalysisRevision(Selection, AnalysisInputs); + std::array readiness_; +}; + +struct AnalysisRequest { + std::uint64_t id; + Operation operation; + Revision revision; +}; +using Ticket = std::shared_ptr; +struct Publication { + Ticket request; + // Exact validated result bytes. Their encoding belongs to the operation/backend. + std::string payload; +}; + +// One slot per selection scope and operation. The owner assigns increasing sequence numbers +// WHEN observing inputs, and installs that observation or invalidates it with a null revision. +// Sequence all document, selection, configuration, lookup, trust and backend changes here, +// including changes to other roots in a rename proof. A watcher gap invalidates its evidence. +// Observations from external systems become effective in this slot at these calls. +class PublicationSlot { + public: + PublicationSlot(const SelectionState &, Operation); + [[nodiscard]] std::expected replace_inputs(std::uint64_t sequence, + Revision revision); + // Accepts a revocation for the owning workspace even while no revision is installed. + // Delayed attempts carrying an older authority generation remain ineligible. + void revoke_trust(const WorkspaceIdentity &, std::uint64_t new_generation); + [[nodiscard]] std::expected issue(); + [[nodiscard]] bool cancel(const Ticket &); + // The adapter associates a validated reply with its original request ticket. + [[nodiscard]] bool publish(const Ticket &, std::string_view validated_payload); + // A retained publication describes the instant of observation. Sequence delivery and edit + // application with the owner, including any subsequent invalidation. + [[nodiscard]] std::shared_ptr current() const; + + private: + struct State { + Revision revision; + Ticket pending; + std::shared_ptr published; + }; + const std::shared_ptr scope_; + const Operation operation_; + mutable std::mutex mutex_; + std::uint64_t sequence_{}, last_request_{}, selection_floor_{}; + std::optional configuration_floor_, trust_floor_, lookup_floor_; + State state_; +}; + +} // namespace Void::LanguageServer::Build diff --git a/include/Void/LanguageServer/Build/Providers.hpp b/include/Void/LanguageServer/Build/Providers.hpp new file mode 100644 index 0000000..3563b1a --- /dev/null +++ b/include/Void/LanguageServer/Build/Providers.hpp @@ -0,0 +1,112 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Build { + +// The launcher binds explicitly selected external inputs to a single workspace. +// Relative producer locators need an independently known producer working directory. +struct ProviderAnchors; +struct ProviderScope { + WorkspaceIdentity workspace; + std::optional exact_database, exact_selector, build_root, producer_cwd; + Workspace::ResourceLimitsConfig limits; + std::shared_ptr anchors; +}; + +enum class FilePurpose { selection, status, database, native_database, response }; +struct ProviderIssue { + std::string code, message; + std::filesystem::path path; +}; +// Bind once when installing launcher grants for this workspace incarnation. +// File readers validate the binding even if a caller copies and edits the scope. +[[nodiscard]] std::expected bind_provider_scope(ProviderScope); +// Reuse captured directories across a new incarnation of the same folder. +[[nodiscard]] std::expected +reuse_provider_scope(const ProviderScope &bound, std::string new_session); +struct ProviderStamp; +struct ProviderFile { + FilePurpose purpose; + std::filesystem::path logical_path, canonical_path; + std::shared_ptr bytes; + std::string content_id; + std::shared_ptr stamp; +}; +[[nodiscard]] std::expected +read_provider_file(const ProviderScope &, const std::filesystem::path &, FilePurpose, + std::size_t byte_limit); +[[nodiscard]] bool provider_file_current(const ProviderScope &, const ProviderFile &); +[[nodiscard]] bool same_provider_object(const ProviderFile &, const ProviderFile &) noexcept; + +// Command paths identify filesystem names. Resolving one never reads its contents. +// A missing direct suffix can name a generated input; an unsafe route has no physical path. +enum class CommandPathKind { file, directory }; +struct CommandPathStamp; +struct CommandPathLookup { + std::filesystem::path logical_path, physical_path; + std::string issue; + std::shared_ptr stamp; +}; +[[nodiscard]] CommandPathLookup inspect_command_path(const ProviderScope &, + const std::filesystem::path &, CommandPathKind); +struct FailedResponseLookup { + ProviderIssue issue; + std::size_t byte_limit{}; +}; +struct CommandLookups { + std::vector paths; + std::vector failed_responses; +}; + +// Only the workspace authority owner supplies an identified driver. Process +// dispatch requires its own check against the current authority generation. +struct DriverInput { + Workspace::ToolCheck tool; + Workspace::CompilerDriver driver; + std::vector wrappers; +}; +struct DatabaseInput { + const ProviderScope &scope; + const ProviderFile &database; + std::optional profile; + std::optional driver; +}; +struct ImportedCommands { + std::vector contexts; + std::vector dependencies; + std::string revision; + CommandLookups lookups; +}; +[[nodiscard]] std::expected import_commands(const DatabaseInput &); + +enum class ProviderHealth { ready, missing, unavailable, invalid, stale, changed, disabled }; +struct ProviderObservation { + std::string provider; + ProviderHealth health{ProviderHealth::unavailable}; + std::optional selection_ticket; + std::optional profile; + std::optional native_generation; + Generation generation; + std::vector issues, warnings; + std::vector inputs; + CommandLookups lookups; +}; +[[nodiscard]] std::optional +changed_provider_input(const ProviderScope &, const ProviderObservation &); +[[nodiscard]] ProviderObservation observe_vbs(const ProviderScope &, const std::filesystem::path &, + const std::optional & = {}); +[[nodiscard]] ProviderObservation observe_compdb(const ProviderScope &, + const std::filesystem::path &, + const std::optional & = {}); + +} // namespace Void::LanguageServer::Build diff --git a/include/Void/LanguageServer/Documents/DocumentSnapshot.hpp b/include/Void/LanguageServer/Documents/DocumentSnapshot.hpp new file mode 100644 index 0000000..db64632 --- /dev/null +++ b/include/Void/LanguageServer/Documents/DocumentSnapshot.hpp @@ -0,0 +1,63 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Documents { + +struct ContentHash { + std::uint64_t fnv1a64{0}; + std::string sha256_hex; + + [[nodiscard]] bool operator==(const ContentHash &other) const noexcept = default; + [[nodiscard]] std::string display_digest() const; +}; + +[[nodiscard]] ContentHash compute_content_hash(std::string_view text); + +enum class DocumentOrigin { overlay, disk }; + +struct DocumentSnapshot { + DocumentIdentity identity; + std::string language_id; + std::optional version; + // Process-local snapshot sequence. Re-reading a disk input can allocate a new snapshot. + std::uint64_t revision_id{0}; + // File overlay membership and encoding generation in the owning document store. + std::uint64_t overlay_epoch{0}; + std::string text; + ContentHash content_hash; + LineIndex line_index; + PositionEncoding encoding{PositionEncoding::utf16}; + DocumentOrigin origin{DocumentOrigin::overlay}; + std::time_t created_at{std::time(nullptr)}; + + // Compare inputs within a session. Disk inputs use the bound physical path, encoding, + // overlay epoch and exact bytes; open overlays have distinct revisions. + [[nodiscard]] bool same_input_as(const DocumentSnapshot &other) const noexcept; + + [[nodiscard]] std::expected + position_to_offset(Position position) const { + return line_index.position_to_offset(text, position, encoding); + } + + [[nodiscard]] std::expected + offset_to_position(std::size_t byte_offset) const { + return line_index.offset_to_position(text, byte_offset, encoding); + } + + [[nodiscard]] std::expected, std::string> + range_to_offsets(Range range) const { + return line_index.range_to_offsets(text, range, encoding); + } +}; + +} // namespace Void::LanguageServer::Documents diff --git a/include/Void/LanguageServer/Documents/DocumentStore.hpp b/include/Void/LanguageServer/Documents/DocumentStore.hpp new file mode 100644 index 0000000..c290cf6 --- /dev/null +++ b/include/Void/LanguageServer/Documents/DocumentStore.hpp @@ -0,0 +1,215 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Documents { + +inline constexpr std::size_t kDefaultMaxDiskDocumentBytes = 16ULL * 1024ULL * 1024ULL; + +struct TextEdit { + std::optional range; + std::string text; +}; + +struct DocumentError { + enum class Kind { + invalid_uri, + invalid_utf8, + not_open, + already_open, + invalid_version, + nonmonotonic_version, + malformed_change, + invalid_range, + desynchronized, + resource_limit, + unavailable_overlay, + ambiguous_overlay, + stale_read, + disk_read_failed, + }; + + Kind kind{Kind::invalid_uri}; + std::string message; +}; + +struct DocumentLimits { + std::size_t max_document_bytes{kDefaultMaxDiskDocumentBytes}; + std::size_t max_snapshot_bytes{128ULL * 1024ULL * 1024ULL}; + std::size_t max_open_documents{4096}; + std::size_t max_unavailable_documents{4096}; + std::size_t max_changes{4096}; + std::size_t max_change_bytes{2 * kDefaultMaxDiskDocumentBytes}; +}; + +inline constexpr std::size_t kDefaultMaxFileOverlayEntries = + DocumentLimits{}.max_open_documents + DocumentLimits{}.max_unavailable_documents; + +struct FileOverlayBinding { + DocumentIdentity identity; + // A unique ready overlay at enumeration time, or the reason its bytes are unavailable. + std::expected, DocumentError> content; +}; + +// A membership witness can outlive enumeration without retaining unrelated open text. +class FileOverlayGeneration { + private: + friend class DocumentStore; + friend class FileOverlayInventory; + friend class BoundSourceObservation; + FileOverlayGeneration() = default; + FileOverlayGeneration(std::shared_ptr store, std::uint64_t epoch) + : store(std::move(store)), epoch(epoch) {} + std::shared_ptr store; + std::uint64_t epoch{}; +}; + +class FileOverlayInventory { + public: + [[nodiscard]] std::span entries() const noexcept { return entries_; } + [[nodiscard]] const FileOverlayGeneration &generation() const noexcept { return generation_; } + + private: + friend class DocumentStore; + friend class BoundSourceObservation; + FileOverlayInventory() = default; + + FileOverlayGeneration generation_; + std::vector entries_; +}; + +class BoundSourceObservation { + public: + [[nodiscard]] const DocumentIdentity &identity() const noexcept { return identity_; } + // Null means the caller may acquire disk bytes through its own bound handle. + [[nodiscard]] const std::shared_ptr &overlay() const noexcept { + return overlay_; + } + + private: + friend class DocumentStore; + BoundSourceObservation() = default; + + FileOverlayGeneration generation_; + DocumentIdentity identity_; + std::shared_ptr overlay_; +}; + +class DocumentStore { + public: + using DiskReadObserver = std::function; + + // The optional observer runs outside the lock after each attempted disk read. + explicit DocumentStore(PositionEncoding encoding = PositionEncoding::utf16, + DocumentLimits limits = {}, DiskReadObserver after_disk_read = {}); + + // Position encoding is negotiated before any document opens. + bool set_position_encoding(PositionEncoding encoding); + [[nodiscard]] PositionEncoding position_encoding() const noexcept; + + [[nodiscard]] std::expected, DocumentError> + open(std::string_view raw_uri, std::string language_id, std::int64_t version, std::string text); + + [[nodiscard]] std::expected, DocumentError> + apply_changes(std::string_view raw_uri, std::int64_t new_version, + std::span edits); + + [[nodiscard]] std::expected + mark_desynchronized(std::string_view raw_uri, std::optional observed_version, + DocumentError cause); + + [[nodiscard]] std::expected close(std::string_view raw_uri); + + [[nodiscard]] std::shared_ptr snapshot(std::string_view raw_uri) const; + [[nodiscard]] std::shared_ptr + snapshot_by_path(const std::filesystem::path &path) const; + + [[nodiscard]] std::vector> list_overlays() const; + + // Captures all local file opens and the membership generation, even for an empty census. + [[nodiscard]] std::expected + file_overlay_inventory(std::size_t max_entries = kDefaultMaxFileOverlayEntries) const; + + // Both names come from the caller's source binding. This operation performs no disk lookup. + // Stage the observation's overlay; an inventory entry can predate a text-only edit. + [[nodiscard]] std::expected + observe_bound_source(const FileOverlayInventory &inventory, std::string_view file_uri, + const std::filesystem::path &physical_path) const; + + // Moves caller-acquired bytes into a budgeted disk snapshot after rechecking absence. + // A changed generation yields stale_read; a live overlay observation yields already_open. + [[nodiscard]] std::expected, DocumentError> + materialize_bound_disk(const BoundSourceObservation &observation, std::string bytes) const; + + // Atomically rechecks membership and every selected document's editor authority. + // The source catalog separately validates disk objects, names, and directory lookups. + [[nodiscard]] std::expected + validate_bound_sources(const FileOverlayInventory &inventory, + std::span selected = {}) const; + [[nodiscard]] std::expected + validate_bound_sources(const FileOverlayGeneration &generation, + std::span selected) const; + + // Resolves a unique, ready overlay before considering a bounded regular-file read. + [[nodiscard]] std::expected, DocumentError> + resolve_content(const std::filesystem::path &path, + std::size_t max_bytes = kDefaultMaxDiskDocumentBytes) const; + + private: + using Snapshot = std::shared_ptr; + using SnapshotResult = std::expected; + + struct OpenDocument { + DocumentIdentity identity; + std::optional language_id; + std::int32_t highest_version; + Snapshot current; + bool admitted; + std::string problem; + }; + + [[nodiscard]] SnapshotResult overlay_for_path(const DocumentIdentity &identity) const; + [[nodiscard]] bool current_generation(const FileOverlayGeneration &generation) const; + [[nodiscard]] std::expected + check_observation(const BoundSourceObservation &observation) const; + [[nodiscard]] std::size_t snapshot_overhead(const DocumentIdentity &identity, + std::string_view language_id) const noexcept; + [[nodiscard]] std::size_t available_snapshot_bytes() const noexcept; + [[nodiscard]] SnapshotResult make_snapshot(const DocumentIdentity &identity, + std::string_view language_id, + std::optional version, + std::string text, + std::optional index = std::nullopt) const; + static void desynchronize(OpenDocument &document, const DocumentError &cause); + + mutable std::shared_mutex mutex_; + const DocumentLimits limits_; + const DiskReadObserver after_disk_read_; + const std::shared_ptr snapshot_bytes_; + PositionEncoding encoding_; + std::uint64_t overlay_epoch_{0}; + std::size_t admitted_documents_{0}; + std::size_t unbound_file_documents_{0}; + bool unknown_file_open_{false}; + bool unknown_virtual_open_{false}; + std::map> by_uri_; + std::multimap by_path_; +}; + +} // namespace Void::LanguageServer::Documents diff --git a/include/Void/LanguageServer/Documents/Position.hpp b/include/Void/LanguageServer/Documents/Position.hpp new file mode 100644 index 0000000..8610bd9 --- /dev/null +++ b/include/Void/LanguageServer/Documents/Position.hpp @@ -0,0 +1,75 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Documents { + +enum class PositionEncoding { + utf16, + utf8, +}; + +inline constexpr auto kMaxPositionValue = + static_cast(std::numeric_limits::max()); + +[[nodiscard]] constexpr std::string_view encoding_name(PositionEncoding encoding) noexcept { + return encoding == PositionEncoding::utf8 ? "utf-8" : "utf-16"; +} + +struct Position { + std::uint32_t line{0}; + std::uint32_t character{0}; + + [[nodiscard]] constexpr auto operator<=>(const Position &other) const noexcept = default; +}; + +struct Range { + Position start{}; + Position end{}; + + [[nodiscard]] constexpr bool operator==(const Range &other) const noexcept = default; +}; + +class LineIndex { + public: + LineIndex() = default; + explicit LineIndex(std::string_view text); + + [[nodiscard]] std::size_t line_count() const noexcept { return line_starts_.size(); } + [[nodiscard]] std::optional line_start_offset(std::uint32_t line) const noexcept; + [[nodiscard]] std::optional + line_content_end_offset(std::string_view text, std::uint32_t line) const noexcept; + + [[nodiscard]] std::expected + position_to_offset(std::string_view text, Position position, PositionEncoding encoding) const; + + [[nodiscard]] std::expected + offset_to_position(std::string_view text, std::size_t byte_offset, + PositionEncoding encoding) const; + + [[nodiscard]] std::expected, std::string> + range_to_offsets(std::string_view text, Range range, PositionEncoding encoding) const; + + private: + friend class DocumentStore; + + LineIndex(std::string_view text, std::size_t line_count); + [[nodiscard]] static std::size_t count_lines(std::string_view text) noexcept; + [[nodiscard]] std::size_t storage_bytes() const noexcept; + [[nodiscard]] bool apply_replacement(std::string_view text, std::size_t start, std::size_t end, + std::string_view replacement, std::size_t max_lines); + + std::vector line_starts_{0}; + std::size_t text_size_{}; +}; + +} // namespace Void::LanguageServer::Documents diff --git a/include/Void/LanguageServer/Documents/Uri.hpp b/include/Void/LanguageServer/Documents/Uri.hpp new file mode 100644 index 0000000..d32d9a7 --- /dev/null +++ b/include/Void/LanguageServer/Documents/Uri.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Documents { + +inline constexpr std::size_t kMaxDocumentUriBytes = 16 * 1024; + +struct DocumentIdentity { + // Client binding key. Filesystem aliases such as separate symlinks have separate keys. + std::string canonical_uri; + std::string display_uri; + // Physical lookup path at binding time. Empty if there is no resolved file path. + std::filesystem::path canonical_path; + bool is_file_uri{false}; + + [[nodiscard]] bool operator==(const DocumentIdentity &other) const noexcept = default; +}; + +// Normalizes the client key and binds the current physical lookup path for local files. +[[nodiscard]] std::expected normalize_uri(std::string_view raw_uri); + +// Normalizes the client key without querying the filesystem. +[[nodiscard]] std::expected client_uri_key(std::string_view raw_uri); + +// Return the original decoded path, preserving symlinks and parent components. +// A valid non-file URI has an empty path. +[[nodiscard]] std::expected +client_file_path(std::string_view raw_uri); + +// Derives the lexical key and physical identity for a local filesystem lookup. +[[nodiscard]] std::expected +identity_from_path(const std::filesystem::path &path); + +[[nodiscard]] std::string path_to_file_uri(const std::filesystem::path &absolute_path); + +} // namespace Void::LanguageServer::Documents diff --git a/include/Void/LanguageServer/Protocol/Framing.hpp b/include/Void/LanguageServer/Protocol/Framing.hpp new file mode 100644 index 0000000..d9875c9 --- /dev/null +++ b/include/Void/LanguageServer/Protocol/Framing.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Protocol { + +inline constexpr std::size_t kDefaultHeaderBytes = 8192; +inline constexpr std::size_t kDefaultBodyBytes = 16777216; + +struct FrameLimits { + std::size_t header_bytes{kDefaultHeaderBytes}; + std::size_t body_bytes{kDefaultBodyBytes}; +}; + +// A disengaged optional means EOF between frames. Framing errors are fatal: the +// caller must not attempt to find another frame in an untrusted byte stream. +[[nodiscard]] std::expected, std::string> +read_frame(std::istream &input, FrameLimits limits = {}); + +[[nodiscard]] std::expected write_frame(std::ostream &output, + std::string_view body); + +// Encoding must succeed before any part of the frame is written. +[[nodiscard]] std::expected +write_json_frame(std::ostream &output, const Json &body, + std::size_t maximum_depth = kDefaultMaxJsonDepth); + +} // namespace Void::LanguageServer::Protocol diff --git a/include/Void/LanguageServer/Protocol/Json.hpp b/include/Void/LanguageServer/Protocol/Json.hpp new file mode 100644 index 0000000..5782a13 --- /dev/null +++ b/include/Void/LanguageServer/Protocol/Json.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Protocol { + +using Json = Void::Json::Strict::Value; +using RequestId = std::variant; + +inline constexpr std::size_t kDefaultMaxJsonDepth = 64; + +// The protocol counts open containers. A scalar needs no depth, and callers can +// lower the protocol limit with maximum_depth. +[[nodiscard]] std::expected +parse_json(std::string_view text, std::size_t maximum_depth = kDefaultMaxJsonDepth); +[[nodiscard]] std::expected +serialize_json(const Json &value, std::size_t maximum_depth = kDefaultMaxJsonDepth); + +[[nodiscard]] std::expected request_id(const Json &value); +[[nodiscard]] Json request_id_json(RequestId id); + +[[nodiscard]] const Json *find_member(const Json::Object &object, std::string_view key) noexcept; +[[nodiscard]] const Json::Object *as_object(const Json *value) noexcept; +[[nodiscard]] const Json::Array *as_array(const Json *value) noexcept; +[[nodiscard]] const std::string *as_string(const Json *value) noexcept; +[[nodiscard]] std::optional as_bool(const Json *value) noexcept; +[[nodiscard]] std::optional as_int64(const Json *value) noexcept; +[[nodiscard]] std::optional as_uint32(const Json *value) noexcept; + +} // namespace Void::LanguageServer::Protocol diff --git a/include/Void/LanguageServer/Support/RegularFile.hpp b/include/Void/LanguageServer/Support/RegularFile.hpp new file mode 100644 index 0000000..9477318 --- /dev/null +++ b/include/Void/LanguageServer/Support/RegularFile.hpp @@ -0,0 +1,135 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace Void::LanguageServer::Detail { + +enum class FileError { + invalid_path, + unavailable, + not_regular, + not_executable, + too_large, + changed, + sink_failed +}; +struct FileInfo { + std::filesystem::path canonical_path; + struct stat metadata; +}; + +inline bool valid_path(const std::filesystem::path &path) { + return !path.empty() && path.native().size() <= 4095 && + path.native().find('\0') == std::string::npos; +} + +inline bool same_file_state(const struct stat &a, const struct stat &b) { + return a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_mode == b.st_mode && + a.st_nlink == b.st_nlink && + a.st_uid == b.st_uid && a.st_gid == b.st_gid && a.st_size == b.st_size && + a.st_mtim.tv_sec == b.st_mtim.tv_sec && a.st_mtim.tv_nsec == b.st_mtim.tv_nsec && + a.st_ctim.tv_sec == b.st_ctim.tv_sec && a.st_ctim.tv_nsec == b.st_ctim.tv_nsec; +} + +// Callers obtain metadata with fstat on their admitted O_PATH descriptor. Both the +// reopened reader and its final state must match that capture before any result is published. +template +std::expected stream_regular_fd(const System::OwnedFd &object, + const struct stat &before, std::uint64_t limit, + bool executable, Sink &&sink) { + if (!S_ISREG(before.st_mode)) { + return std::unexpected(FileError::not_regular); + } + if (executable && ((before.st_mode & 0111) == 0 || + ::faccessat(object.get(), "", X_OK, AT_EMPTY_PATH | AT_EACCESS) != 0)) { + return std::unexpected(FileError::not_executable); + } + if (before.st_size < 0 || static_cast(before.st_size) > limit) { + return std::unexpected(FileError::too_large); + } + const auto descriptor = "/proc/self/fd/" + std::to_string(object.get()); + const System::OwnedFd input{ + ::open(descriptor.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOCTTY)}; + struct stat opened{}; + if (!input || ::fstat(input.get(), &opened) != 0) { + return std::unexpected(FileError::unavailable); + } + if (!same_file_state(before, opened)) { + return std::unexpected(FileError::changed); + } + std::array buffer; + auto remaining = static_cast(before.st_size); + for (;;) { + // One extra byte distinguishes a growing/pseudo file from the promised EOF. + const auto amount = std::min(buffer.size(), remaining + 1); + const auto n = ::read(input.get(), buffer.data(), amount); + if (n < 0) { + if (errno == EINTR) { + continue; + } + return std::unexpected(FileError::unavailable); + } + if (n == 0) { + break; + } + if (static_cast(n) > remaining) { + return std::unexpected(FileError::changed); + } + if (!sink(std::span{buffer.data(), static_cast(n)})) { + return std::unexpected(FileError::sink_failed); + } + remaining -= static_cast(n); + } + struct stat after{}; + if (remaining != 0 || ::fstat(input.get(), &after) != 0 || !same_file_state(before, after)) { + return std::unexpected(FileError::changed); + } + return {}; +} + +// Linux release target. O_PATH identifies the referent without opening a device or blocking on a +// FIFO. The selected-file API also checks the caller's original name after streaming. +template +std::expected read_regular(const std::filesystem::path &path, + std::uint64_t limit, bool executable, Sink sink) { + if (!valid_path(path) || !path.is_absolute()) { + return std::unexpected(FileError::invalid_path); + } + const System::OwnedFd object{::open(path.c_str(), O_PATH | O_CLOEXEC)}; + struct stat before{}; + if (!object || ::fstat(object.get(), &before) != 0) { + return std::unexpected(FileError::unavailable); + } + std::error_code ec; + auto canonical = std::filesystem::canonical(path, ec); + if (ec) { + return std::unexpected(FileError::unavailable); + } + auto read = stream_regular_fd(object, before, limit, executable, sink); + if (!read) { + return std::unexpected(read.error()); + } + struct stat named{}; + if (std::filesystem::canonical(path, ec) != canonical || ec || + ::stat(canonical.c_str(), &named) != 0 || !same_file_state(before, named)) { + return std::unexpected(FileError::changed); + } + return FileInfo{std::move(canonical), before}; +} + +} // namespace Void::LanguageServer::Detail diff --git a/include/Void/LanguageServer/Workspace/Configuration.hpp b/include/Void/LanguageServer/Workspace/Configuration.hpp new file mode 100644 index 0000000..57c10ad --- /dev/null +++ b/include/Void/LanguageServer/Workspace/Configuration.hpp @@ -0,0 +1,159 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Workspace { + +enum class ConfigLayer { defaults, workspace_local, user_runtime, cli }; +struct ConfigOrigin { + ConfigLayer layer{ConfigLayer::defaults}; + std::filesystem::path base; + std::optional selected_file; + std::uint64_t revision{}; // Assigned at trusted input ingress; copying/remerging preserves it. +}; +enum class ProviderPreference { auto_detect, vbs, compdb, none }; +enum class AuthorityLevel { + passive_read, + trusted_metadata_refresh, + compiler_use, + explicit_build_action +}; + +struct ToolSelection { + std::filesystem::path root; + AuthorityLevel operation{AuthorityLevel::passive_read}; + std::filesystem::path executable; + bool operator==(const ToolSelection &) const = default; +}; + +struct ResourceLimitsConfig { + std::uint32_t max_semantic_workers{2}; + std::uint32_t worker_memory_limit_mib{2048}; + std::uint32_t max_response_file_depth{8}; + std::size_t max_response_file_bytes{1024ULL * 1024ULL}; + std::size_t max_compdb_bytes{64ULL * 1024ULL * 1024ULL}; + std::size_t max_manifest_bytes{32ULL * 1024ULL * 1024ULL}; +}; + +enum class ConfigIssue { + invalid_value, + invalid_origin, + unsupported, + untrusted_setting, + resource_limit, + file_error +}; +struct ConfigDiagnostic { + ConfigLayer source_layer; + std::string key; + std::string message; + ConfigIssue issue; +}; + +// Typed input for launcher flags. Paths are interpreted relative to the supplied CLI base. +struct SettingsOverrides { + std::optional provider; + std::optional vbs_manifest_path; + std::optional compdb_path; + std::optional selected_profile; + std::optional enable_background_indexing; + std::optional max_semantic_workers; + std::optional worker_memory_limit_mib; + std::optional max_response_file_depth; + std::optional max_response_file_bytes; + std::optional max_compdb_bytes; + std::optional max_manifest_bytes; + std::optional> trusted_roots; + std::optional> approved_compilers; + std::optional> approved_wrappers; + std::optional allow_metadata_refresh; + std::optional allow_explicit_build_actions; + std::optional allow_compiler_plugins; + std::optional> tool_approvals; +}; + +class PartialWorkspaceSettings { + public: + [[nodiscard]] const ConfigOrigin &origin() const noexcept { return origin_; } + [[nodiscard]] const auto &diagnostics() const noexcept { return diagnostics_; } + + private: + PartialWorkspaceSettings(ConfigOrigin, SettingsOverrides, std::vector); + static std::uint64_t latest_trusted_revision() noexcept; + ConfigOrigin origin_; + SettingsOverrides values_; + std::vector diagnostics_; + + friend PartialWorkspaceSettings parse_workspace_settings(const Protocol::Json &, + const std::filesystem::path &); + friend std::expected + read_user_settings(const std::filesystem::path &); + friend PartialWorkspaceSettings settings_from_cli(SettingsOverrides, + const std::filesystem::path &); + friend class MergedConfiguration; + friend class TrustPolicy; +}; + +struct WorkspaceSettings { + std::filesystem::path workspace_root; + ProviderPreference provider{ProviderPreference::auto_detect}; + std::optional vbs_manifest_path; + ConfigOrigin vbs_manifest_origin; + std::optional compdb_path; + ConfigOrigin compdb_origin; + std::optional selected_profile; + bool enable_background_indexing{true}; + ResourceLimitsConfig limits{}; + + // The legacy lists remain configuration data. Only an exact toolApprovals entry selects a pin. + std::vector trusted_roots; + std::vector approved_compilers; + std::vector approved_wrappers{"ccache", "sccache", "distcc"}; + bool allow_metadata_refresh{false}; + bool allow_explicit_build_actions{false}; + bool allow_compiler_plugins{false}; + std::vector tool_approvals; + ConfigOrigin tool_approvals_origin; +}; + +class MergedConfiguration { + public: + [[nodiscard]] const WorkspaceSettings &effective() const noexcept { return effective_; } + [[nodiscard]] const auto &diagnostics() const noexcept { return diagnostics_; } + + private: + MergedConfiguration() = default; + WorkspaceSettings effective_; + std::vector diagnostics_; + std::optional metadata_refresh_, build_actions_; + void apply(const PartialWorkspaceSettings &, ConfigLayer); + friend MergedConfiguration merge_configuration(const PartialWorkspaceSettings &, + const PartialWorkspaceSettings *, + const PartialWorkspaceSettings *); +}; + +[[nodiscard]] PartialWorkspaceSettings +parse_workspace_settings(const Protocol::Json &payload, + const std::filesystem::path &workspace_root); +// The launcher explicitly selects this absolute file. No repository discovery or cwd fallback. +[[nodiscard]] std::expected +read_user_settings(const std::filesystem::path &selected_file); +[[nodiscard]] PartialWorkspaceSettings settings_from_cli(SettingsOverrides options, + const std::filesystem::path &base); +[[nodiscard]] MergedConfiguration +merge_configuration(const PartialWorkspaceSettings &workspace, + const PartialWorkspaceSettings *user = nullptr, + const PartialWorkspaceSettings *cli = nullptr); +[[nodiscard]] std::string_view provider_preference_name(ProviderPreference pref) noexcept; +[[nodiscard]] bool is_transparent_wrapper(std::string_view name) noexcept; + +} // namespace Void::LanguageServer::Workspace diff --git a/include/Void/LanguageServer/Workspace/Trust.hpp b/include/Void/LanguageServer/Workspace/Trust.hpp new file mode 100644 index 0000000..40a1ea5 --- /dev/null +++ b/include/Void/LanguageServer/Workspace/Trust.hpp @@ -0,0 +1,165 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Workspace { + +enum class TrustError { + invalid_path, + unavailable_file, + not_regular, + not_executable, + too_large, + digest_unavailable, + identity_changed, + untrusted_root, + operation_not_approved, + tool_not_approved, + tool_not_pinned, + stale_generation, + explicit_action_required, + invalid_invocation, + action_pending, + action_not_current, + invocation_mismatch, + capacity_exceeded +}; +[[nodiscard]] std::string_view trust_error_message(TrustError error) noexcept; + +struct ToolIdentity { + std::filesystem::path selected_path; + std::filesystem::path canonical_path; + std::uint64_t device{}, inode{}, file_size{}; + std::uint32_t mode{}, owner{}, group{}; + std::string content_hash_hex; + bool operator==(const ToolIdentity &) const = default; +}; + +inline constexpr std::uint64_t max_tool_bytes = 256ULL * 1024 * 1024; +[[nodiscard]] std::expected +inspect_tool_identity(const std::filesystem::path &executable); +[[nodiscard]] std::expected +revalidate_tool_identity(const ToolIdentity &pinned); + +enum class CompilerDriver { unknown, gcc, clang }; +enum class FlagClassification { + safe, + transparent_wrapper, + invalid_command, + unapproved_compiler_path, + unsupported_driver, + execution_bearing_plugin, + execution_bearing_wrapper, + suspicious_toolchain_override, + unresolved_response_file, + unsupported_option, + unsupported_operand +}; +struct CommandSecurityReport { + bool allowed{}; + FlagClassification classification{FlagClassification::invalid_command}; + std::size_t argument_index{}; + std::string_view reason; + std::vector unwrapped_argv; + std::vector unwrapped_wrappers; +}; + +// Describes a normalized GCC/Clang C/C++ argv. The provider expands response files and +// resolves supported path operands first. Only the accepted data suffix appears in unwrapped_argv. +[[nodiscard]] CommandSecurityReport +classify_and_unwrap_command(std::span argv, + std::span recognized_wrappers, + const ToolIdentity &selected_compiler, CompilerDriver driver); + +struct ToolCheck { + ToolIdentity identity; + std::filesystem::path workspace_root; + AuthorityLevel operation; + std::uint64_t trust_generation; + ConfigOrigin selection_origin; +}; + +struct BuildInvocation { + std::filesystem::path root, executable, working_directory; + std::vector arguments; // excludes executable, order is significant + std::string input_identity, environment_identity; + std::uint64_t trust_generation{}; + bool operator==(const BuildInvocation &other) const; +}; + +class BuildApproval { + friend class TrustPolicy; + BuildApproval(std::shared_ptr invocation, + std::pair cwd) + : invocation_(std::move(invocation)), directory_(cwd) {} + std::shared_ptr invocation_; + std::pair directory_; +}; + +// A ToolCheck describes one passive observation. A future dispatcher must bind the verified +// open object, exact invocation and current generation at dispatch; a path/report is insufficient. +class TrustPolicy { + public: + // Observers may reenter. Concurrent callbacks carry their committed workspace generations. + using RevocationCallback = + std::move_only_function; + explicit TrustPolicy(RevocationCallback on_revocation = {}); + + // Launcher-side configuration install/refresh. Invalidates the old pins, work and pending + // action. + [[nodiscard]] std::expected + replace_configuration(const MergedConfiguration &configuration); + [[nodiscard]] std::expected + pin_approved_tool(const std::filesystem::path &root, AuthorityLevel purpose, + const std::filesystem::path &executable); + [[nodiscard]] std::expected + check_tool(const std::filesystem::path &root, AuthorityLevel purpose, + const std::filesystem::path &executable, std::uint64_t expected_generation); + void revoke_root_authority(const std::filesystem::path &root); + [[nodiscard]] std::uint64_t generation(const std::filesystem::path &root) const; + + // Only a new explicit user action may call approve_build_action. Consuming/cancelling its + // ticket is atomic. Every copy of a spent or revoked ticket is ineligible. + [[nodiscard]] std::expected + approve_build_action(const BuildInvocation &invocation); + [[nodiscard]] std::expected + consume_build_action(const BuildApproval &approval, const BuildInvocation &invocation); + [[nodiscard]] bool cancel_build_action(const BuildApproval &approval); + + private: + using Key = std::pair; + using DirectoryId = std::pair; + struct RootState { + DirectoryId directory; + ConfigOrigin origin; + std::uint64_t approval_floor{}; // Previously read selections cannot re-arm a revoked pin. + std::uint64_t generation{}; + std::map> tools; + std::shared_ptr pending; + }; + std::expected + inspect_selected(const std::filesystem::path &root, AuthorityLevel purpose, + const std::filesystem::path &executable, + std::optional required_generation); + void notify(const std::filesystem::path &root, std::uint64_t generation) const; + mutable std::mutex mutex_; + std::uint64_t last_generation_{}; + std::map roots_; + RevocationCallback on_revocation_; +}; + +} // namespace Void::LanguageServer::Workspace diff --git a/include/vls/DocumentSync.hpp b/include/vls/DocumentSync.hpp new file mode 100644 index 0000000..c3a596d --- /dev/null +++ b/include/vls/DocumentSync.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include +#include + +namespace vls { + +[[nodiscard]] Void::LanguageServer::Documents::PositionEncoding +negotiate_position_encoding(const Void::LanguageServer::Protocol::Json &initialize_params); + +void reject_change_envelope(Void::LanguageServer::Documents::DocumentStore &store, + const Void::LanguageServer::Protocol::Json *params); + +[[nodiscard]] std::expected +synchronize_document(Void::LanguageServer::Documents::DocumentStore &store, std::string_view method, + const Void::LanguageServer::Protocol::Json *params); + +} // namespace vls diff --git a/include/vls/Framing.hpp b/include/vls/Framing.hpp index 5fa2b4c..336f536 100644 --- a/include/vls/Framing.hpp +++ b/include/vls/Framing.hpp @@ -1,25 +1,11 @@ #pragma once -#include -#include -#include -#include -#include -#include +#include namespace vls { -struct FrameLimits { - std::size_t header_bytes{8192}; - std::size_t body_bytes{16777216}; -}; - -// A disengaged optional means EOF between frames. Framing errors are fatal: the -// caller must not attempt to find another frame in an untrusted byte stream. -[[nodiscard]] std::expected, std::string> -read_frame(std::istream &input, FrameLimits limits = {}); - -[[nodiscard]] std::expected write_frame(std::ostream &output, - std::string_view body); +using Void::LanguageServer::Protocol::FrameLimits; +using Void::LanguageServer::Protocol::read_frame; +using Void::LanguageServer::Protocol::write_frame; } // namespace vls diff --git a/include/vls/Json.hpp b/include/vls/Json.hpp index 4e74c99..5469747 100644 --- a/include/vls/Json.hpp +++ b/include/vls/Json.hpp @@ -1,23 +1,36 @@ #pragma once -#include +#include -#include -#include -#include -#include -#include -#include +#include +#include namespace vls { -using Json = Void::Json::Strict::Value; -using RequestId = std::variant; +using Void::LanguageServer::Protocol::Json; +using Void::LanguageServer::Protocol::parse_json; +using Void::LanguageServer::Protocol::request_id; +using Void::LanguageServer::Protocol::RequestId; -[[nodiscard]] std::expected parse_json(std::string_view text, - std::size_t maximum_depth = 64); -[[nodiscard]] std::expected request_id(const Json &value); -[[nodiscard]] std::string quote_json(std::string_view text); -[[nodiscard]] std::string encode_id(const RequestId &id); +namespace detail { + +inline std::string require_json_encoding(std::expected encoded) { + if (!encoded) { + throw std::invalid_argument{encoded.error()}; + } + return std::move(*encoded); +} + +} // namespace detail + +[[nodiscard]] inline std::string quote_json(std::string_view text) { + return detail::require_json_encoding( + Void::LanguageServer::Protocol::serialize_json(Json{std::string{text}})); +} + +[[nodiscard]] inline std::string encode_id(const RequestId &id) { + return detail::require_json_encoding(Void::LanguageServer::Protocol::serialize_json( + Void::LanguageServer::Protocol::request_id_json(id))); +} } // namespace vls diff --git a/include/vls/Server.hpp b/include/vls/Server.hpp index d911b82..4d8b1f6 100644 --- a/include/vls/Server.hpp +++ b/include/vls/Server.hpp @@ -1,32 +1,44 @@ #pragma once +#include #include +#include +#include #include #include #include #include namespace vls { +namespace semantic { +class EditorDiagnostics; +} inline constexpr std::string_view server_version = "0.1.0"; struct DispatchResult { std::optional response; std::optional exit_code; + std::string diagnostic{}; }; class Server { public: + explicit Server(WorkspaceLaunch launch = {}, std::function send = {}); + ~Server(); [[nodiscard]] DispatchResult handle(std::string_view body); private: enum class State { awaiting_initialize, running, shutdown }; State state_{State::awaiting_initialize}; + Void::LanguageServer::Documents::DocumentStore documents_; + WorkspaceSession workspace_; + std::unique_ptr diagnostics_; }; // Thin transport loop shared by the executable and stream-failure unit tests. [[nodiscard]] int run_stdio(std::istream &input, std::ostream &output, std::ostream &diagnostics, - FrameLimits limits = {}); + FrameLimits limits = {}, WorkspaceLaunch launch = {}); } // namespace vls diff --git a/include/vls/WorkspaceSession.hpp b/include/vls/WorkspaceSession.hpp new file mode 100644 index 0000000..2311191 --- /dev/null +++ b/include/vls/WorkspaceSession.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls { + +namespace semantic { +class GccProfile; +} + +struct WorkspaceLaunch { + std::optional root, build_root, producer_cwd; + std::optional user_settings, + cli_settings; + std::shared_ptr diagnostics_profile{}; +}; + +struct SemanticDriver { + std::filesystem::path executable; + Void::LanguageServer::Workspace::CompilerDriver family{ + Void::LanguageServer::Workspace::CompilerDriver::unknown}; +}; + +enum class SemanticContextIssue { unavailable, disabled, no_command, wrong_command, superseded }; + +struct SemanticContextError { + SemanticContextIssue issue; + std::string message; +}; + +struct SemanticLeaseData; +class SemanticContextLease { + public: + [[nodiscard]] const Void::LanguageServer::Build::Selection &selection() const; + [[nodiscard]] const Void::LanguageServer::Build::SelectionState &selection_state() const; + [[nodiscard]] const Void::LanguageServer::Build::DriverInput &driver() const; + [[nodiscard]] std::uint64_t configuration_generation() const; + [[nodiscard]] std::uint32_t worker_memory_limit_mib() const; + [[nodiscard]] const std::string &document_uri() const; + + private: + friend class WorkspaceSession; + explicit SemanticContextLease(std::shared_ptr data); + std::shared_ptr data_; +}; + +class WorkspaceSession { + public: + // The optional test hook runs after observation and before the publication checks. + explicit WorkspaceSession(WorkspaceLaunch = {}, std::function before_publish = {}); + ~WorkspaceSession(); + + // The client settings object contains defaults and optional `workspaces` + // overrides keyed by a folder's admitted or canonical file URI. + [[nodiscard]] std::expected + initialize(const Void::LanguageServer::Protocol::Json ¶ms); + [[nodiscard]] std::expected + update_folders(const Void::LanguageServer::Protocol::Json *params); + [[nodiscard]] std::expected + configure(const Void::LanguageServer::Protocol::Json *params); + [[nodiscard]] std::expected + provider_status(const Void::LanguageServer::Protocol::Json *params); + + // The caller explicitly selects the launcher driver. The lease retains the ordered + // original and checked command in selection()->selected, and its immutable generation. + [[nodiscard]] std::expected + acquire_semantic_context(std::string_view document_uri, + std::optional workspace_uri, + const SemanticDriver &selected_driver); + [[nodiscard]] std::expected + validate_semantic_context(const SemanticContextLease &lease); + + // Invalidates launcher authority and in-flight observations for an admitted root. + void revoke_root_authority(const std::filesystem::path &root); + + private: + struct State; + std::unique_ptr state_; +}; + +} // namespace vls diff --git a/include/vls/debug/inspection/ReplaySession.hpp b/include/vls/debug/inspection/ReplaySession.hpp new file mode 100644 index 0000000..ccac2e2 --- /dev/null +++ b/include/vls/debug/inspection/ReplaySession.hpp @@ -0,0 +1,66 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace vls::gcc { +class ReplayRecording; +} + +namespace vls::debug { +namespace Protocol = Void::LanguageServer::Protocol; +using Json = Protocol::Json; + +// DAP and the versioned inspection requests share the same cursor and generation. +class ReplaySession { + public: + static std::expected open(const std::filesystem::path &path); + ReplaySession(const ReplaySession &) = delete; + ReplaySession &operator=(const ReplaySession &) = delete; + ReplaySession(ReplaySession &&) noexcept = default; + ReplaySession &operator=(ReplaySession &&) = delete; + + [[nodiscard]] Json::Object identity() const; + [[nodiscard]] Json::Object describe() const; + [[nodiscard]] bool matches(const Json::Object &arguments) const; + [[nodiscard]] std::expected timeline(std::size_t start, + std::size_t count) const; + [[nodiscard]] std::expected frames(std::size_t start, + std::size_t count) const; + + // A false result represents the boundary in the requested direction. It preserves the cursor. + [[nodiscard]] std::expected initial_position(); + [[nodiscard]] std::expected move_to_value(bool forward); + [[nodiscard]] std::expected seek(std::uint32_t sequence); + void finish(); + [[nodiscard]] bool paused() const { return sequence_.has_value(); } + [[nodiscard]] std::string_view pause_kind() const { return pause_kind_; } + [[nodiscard]] bool source_available() const { return source_available_; } + [[nodiscard]] std::string_view source_bytes() const; + [[nodiscard]] std::size_t frame_count() const; + [[nodiscard]] const Json &frame(std::size_t top_first_index) const; + [[nodiscard]] std::int64_t frame_handle(std::size_t index) const; + [[nodiscard]] std::int64_t scope_handle(std::size_t index) const; + [[nodiscard]] std::optional handle_index(std::int64_t handle, bool scope) const; + + private: + ReplaySession(std::shared_ptr recording, std::string id); + std::shared_ptr recording_; + std::string id_; + bool source_available_; + bool finished_{}; + std::int64_t generation_{}; + std::int64_t next_handle_{1}; + std::int64_t frame_base_{1}; + std::optional sequence_; + std::string_view pause_kind_{"none"}; + Json cursor_{nullptr}; +}; +} // namespace vls::debug diff --git a/include/vls/debug/live/LiveSession.hpp b/include/vls/debug/live/LiveSession.hpp new file mode 100644 index 0000000..1743290 --- /dev/null +++ b/include/vls/debug/live/LiveSession.hpp @@ -0,0 +1,66 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::debug::live { + +enum class State { idle, running, stopped, completed, failed, cancelled }; + +struct Stop { + std::uint64_t generation{}; + std::uint32_t sequence{}; +}; + +struct Options { + std::filesystem::path worker; // vls_gcc_probe + std::filesystem::path compiler; + std::string compiler_sha256; + std::filesystem::path source; + std::filesystem::path trace; + bool stepping{true}; + std::chrono::milliseconds deadline{60000}; + std::size_t max_notice_bytes{64 * 1024}; +}; + +// One live private-compiler session speaking the supervisor notice protocol. +// Control actions are serialized; an inspection snapshot belongs to the stop +// generation that requested it and is not reused after the session moves. +class LiveSession { + public: + explicit LiveSession(Options); + ~LiveSession(); + LiveSession(const LiveSession &) = delete; + LiveSession &operator=(const LiveSession &) = delete; + LiveSession(LiveSession &&) = delete; + LiveSession &operator=(LiveSession &&) = delete; + + // Spawns the worker and waits for the first stop. + [[nodiscard]] std::expected start(); + // At a stop: single-step. Returns the next stop or nullopt when finished. + [[nodiscard]] std::expected, std::string> step(); + [[nodiscard]] std::expected, std::string> continue_run(); + // Requests cancellation and reaps the worker. + [[nodiscard]] std::expected cancel(); + // Read-only bounded snapshot at the current stop. + [[nodiscard]] std::expected inspect(); + + [[nodiscard]] State state() const; + [[nodiscard]] std::optional stop() const; + [[nodiscard]] std::string outcome() const; + [[nodiscard]] std::string reason() const; + + private: + struct State_; + std::unique_ptr state_; +}; + +} // namespace vls::debug::live diff --git a/include/vls/features/Completion.hpp b/include/vls/features/Completion.hpp new file mode 100644 index 0000000..b5e8852 --- /dev/null +++ b/include/vls/features/Completion.hpp @@ -0,0 +1,95 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace vls::features::completion { + +// Candidate origin is explicit: this slice ranks workspace symbols from the +// analysis index and never claims compiler-native completion. +enum class Kind { unknown, function, type, variable, field, namespace_, module, keyword }; + +struct Limits { + std::size_t candidates{200}; + std::size_t labelBytes{256}; + std::size_t detailBytes{512}; + std::size_t provenanceBytes{128}; +}; + +// Stable identity of one completion candidate across a later resolve request. +struct Identity { + std::string name; + std::string path; + std::uint32_t line{}, character{}; + auto operator<=>(const Identity &) const = default; +}; + +struct Candidate { + std::string label; + Kind kind{Kind::unknown}; + std::string detail; + std::string provenance; + Identity identity; + auto operator<=>(const Candidate &) const = default; +}; + +struct Item { + std::string label; + Kind kind{Kind::unknown}; + std::string detail; + std::string provenance; + std::string sort_text; + Identity identity; + // Byte offsets of the identifier prefix the item replaces. + std::size_t replacement_start{}, replacement_end{}; + auto operator<=>(const Item &) const = default; +}; + +struct Result { + std::vector items; + // True until compiler-native completion exists; index candidates are not + // authoritative for visibility or accessibility. + bool incomplete{true}; + std::string backend{"symbol-index"}; +}; + +// Longest ASCII identifier prefix ending at the byte offset. Empty when the +// preceding text is not an identifier or the prefix starts with a digit. +[[nodiscard]] std::string_view prefix_at(std::string_view text, std::size_t offset); + +// Filters candidates whose label starts with the prefix, deduplicates by label +// and kind, ranks deterministically (kind priority, shorter label, label) and +// bounds every field. The replacement range covers the prefix. +[[nodiscard]] Result complete(std::span, std::string_view text, std::size_t offset, + const Limits & = Limits{}); + +// A candidate as the current index generation reports it. +struct Detail { + Identity identity; + Kind kind{Kind::unknown}; + std::string detail; + std::string provenance; + auto operator<=>(const Detail &) const = default; +}; + +struct Resolved { + enum class Status { resolved, stale, unknown }; + Status status{Status::unknown}; + std::string documentation; + std::string detail; +}; + +// Resolves a captured candidate identity against the current generation. +// A changed generation is stale and an absent identity is unknown; neither +// ever returns details for a different entity. Documentation is bounded and +// fenced so that editor rendering cannot be escaped by the content. +[[nodiscard]] Resolved resolve(const Identity &, std::uint64_t captured_generation, + std::uint64_t current_generation, std::span, + const Limits & = Limits{}); + +} // namespace vls::features::completion diff --git a/include/vls/features/IndexNavigation.hpp b/include/vls/features/IndexNavigation.hpp new file mode 100644 index 0000000..a6eb035 --- /dev/null +++ b/include/vls/features/IndexNavigation.hpp @@ -0,0 +1,34 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace vls::features { + +// What the caller currently knows about one source path. Content identity is +// the same opaque value the index stored; an empty identity means the caller +// cannot prove the file's current content, so its facts stay non-editable. +struct IndexedSource { + std::string path; + std::string content; + bool editable{}; +}; + +// Merges one published index generation into a navigation fact set. +// +// Contexts the set does not know yet are added with the index's completeness. +// Each record's use location and every proven reference become facts whose +// binding joins on name and definition. Facts are deduplicated by binding, +// source and use; an existing fact always wins, so compiler-derived content +// identities are never replaced by weaker index data. A record whose source +// is unknown stays in the set as a non-editable fact: rename then refuses +// instead of editing an unverified file. Returns the number of added facts. +std::size_t ingest_index_facts(navigation::FactSet &, const index::Generation &, + std::span, std::size_t limit = 65536); + +} // namespace vls::features diff --git a/include/vls/features/SignatureHelp.hpp b/include/vls/features/SignatureHelp.hpp new file mode 100644 index 0000000..a2f697e --- /dev/null +++ b/include/vls/features/SignatureHelp.hpp @@ -0,0 +1,62 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace vls::features::signature { + +struct Limits { + std::size_t signatures{8}; + std::size_t parameters{64}; + std::size_t labelBytes{1024}; + std::size_t parameterBytes{256}; + std::size_t scanBytes{64 * 1024}; +}; + +struct Parameter { + std::string label; + // Byte range of label within the signature label, when it can be located. + std::optional> range; + auto operator<=>(const Parameter &) const = default; +}; + +struct Signature { + std::string label; + std::vector parameters; + auto operator<=>(const Signature &) const = default; +}; + +struct Result { + std::vector signatures; + std::uint32_t active_signature{}; + std::uint32_t active_parameter{}; +}; + +// Splits one compiler signature into a label and its parameter list. Commas +// nested in (), [], {} or a plausible template argument list do not separate +// parameters. A signature without a parameter list keeps an empty list. +[[nodiscard]] Signature parse(std::string_view signature, const Limits & = Limits{}); + +// Number of the active parameter at the byte offset: top-level commas between +// the innermost open parenthesis and the offset, ignoring literals, comments +// and nested brackets. The backward scan is bounded by the limit. +[[nodiscard]] std::uint32_t active_parameter(std::string_view text, std::size_t offset, + const Limits & = Limits{}); + +// True when the offset lies inside the argument list opened after the callee +// span [use_start, use_end): the first '(' after the span and its matching ')' +// must enclose the offset. The scan is bounded and ignores literals/comments. +[[nodiscard]] bool in_call(std::string_view text, std::size_t use_start, std::size_t use_end, + std::size_t offset, const Limits & = Limits{}); + +// Complete signature help for a call site. Empty or malformed signatures are +// skipped; an empty result means no signature is available. +[[nodiscard]] Result build(std::span signatures, std::string_view text, + std::size_t offset, const Limits & = Limits{}); + +} // namespace vls::features::signature diff --git a/include/vls/index/SymbolIndex.hpp b/include/vls/index/SymbolIndex.hpp new file mode 100644 index 0000000..dea382a --- /dev/null +++ b/include/vls/index/SymbolIndex.hpp @@ -0,0 +1,158 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::index { + +// Zero-based LSP-style character coordinates within one physical line. +struct Location { + std::string path; + std::uint32_t line{}, character{}; + std::uint32_t endLine{}, endCharacter{}; + auto operator<=>(const Location &) const = default; +}; + +enum class SymbolKind { unknown, function, type, variable, field, namespace_, module }; + +struct SymbolRecord { + std::string name; + SymbolKind kind{SymbolKind::unknown}; + Location location; // declaration or definition + std::optional definition; + std::vector references; + std::string provenance; + auto operator<=>(const SymbolRecord &) const = default; +}; + +struct Limits { + std::size_t contexts{64}; + std::size_t records{65536}; + std::size_t recordsPerContext{16384}; + std::size_t referencesPerRecord{256}; + std::size_t nameBytes{256}; + std::size_t pathBytes{4096}; + std::size_t snapshotBytes{32 * 1024 * 1024}; +}; + +struct ContextInput { + std::string context; // Build::ContextKey alternative + std::vector dependencies; + // Path and content identity of every source this context consumed. + std::vector> sources; + std::vector records; + bool complete{true}; + std::string reason; +}; + +struct Coverage { + bool indexed{}; // at least one context or overlay was considered + bool complete{}; + std::vector incomplete; // context names, sorted + auto operator<=>(const Coverage &) const = default; +}; + +struct Query { + std::string name; + bool substring{}; + std::optional context; + std::size_t limit{100}; +}; + +struct Result { + std::vector symbols; + Coverage coverage; + bool truncated{}; +}; + +// Immutable published snapshot. Readers keep it alive across later publications +// and evictions. +class Generation { + public: + [[nodiscard]] std::uint64_t number() const noexcept { return number_; } + [[nodiscard]] const std::vector &symbols() const noexcept { return records_; } + [[nodiscard]] const std::vector> &contexts() const noexcept { + return contexts_; + } + + private: + friend class SymbolIndex; + Generation(std::uint64_t number, std::vector records, + std::vector> contexts) + : number_(number), records_(std::move(records)), contexts_(std::move(contexts)) {} + std::uint64_t number_; + std::vector records_; + std::vector> contexts_; +}; + +// Context-aware, bounded symbol index. Committed records belong to explicit +// analysis contexts; unsaved document overlays shadow committed records for +// the same path and are reconciled on save/close. A changed, deleted or +// renamed source marks dependent contexts incomplete without discarding the +// last-good records (degraded navigation, never an authoritative rename). +class SymbolIndex { + public: + explicit SymbolIndex(Limits = Limits{}); + ~SymbolIndex(); + SymbolIndex(const SymbolIndex &) = delete; + SymbolIndex &operator=(const SymbolIndex &) = delete; + + // Atomically replaces one context and publishes a new generation. + [[nodiscard]] bool publish(const ContextInput &); + [[nodiscard]] bool remove(std::string_view context); + + // Unsaved document records. The newest overlay for a path shadows the + // committed records of that path until it is cleared. + [[nodiscard]] bool set_overlay(std::string path, std::string content, + std::vector records); + [[nodiscard]] bool clear_overlay(std::string_view path); + + // A new content (or absence) invalidates every context that consumed the + // path. Matching content is a no-op. + [[nodiscard]] std::size_t invalidate(std::string_view path, + const std::optional &content); + + [[nodiscard]] Result find(const Query &) const; + [[nodiscard]] Coverage coverage() const; + [[nodiscard]] std::shared_ptr current() const; + [[nodiscard]] std::uint64_t generation() const; + [[nodiscard]] std::size_t records() const; + [[nodiscard]] const Limits &limits() const noexcept; + + // Versioned persistence. restore() classifies the snapshot; incompatible or + // corrupt bytes are quarantined and the index rebuilds into a new generation. + enum class LoadStatus { loaded, missing, incompatible, corrupt, oversized }; + struct LoadResult { + LoadStatus status{LoadStatus::missing}; + std::uint64_t generation{}; + std::optional quarantine; + // True when a schema-1 snapshot was accepted and upgraded in memory. + bool migrated{}; + }; + // Writes the versioned snapshot (schema 2 with a canonical payload digest). + // restore() also accepts schema 1 and reports the upgrade as migrated. + [[nodiscard]] bool save(const std::filesystem::path &) const; + [[nodiscard]] std::expected restore(const std::filesystem::path &); + // True only when a compatible snapshot was loaded. + [[nodiscard]] bool load(const std::filesystem::path &); + // Generation-directory backend: each save keeps the previous generation for + // crash recovery, CURRENT selects the newest, and a legacy index.json is + // migrated on the first restore. + [[nodiscard]] bool save_generation(const std::filesystem::path &); + [[nodiscard]] std::expected + restore_generation(const std::filesystem::path &); + + private: + struct State; + std::shared_ptr state_; +}; + +} // namespace vls::index diff --git a/include/vls/modules/ArtifactCache.hpp b/include/vls/modules/ArtifactCache.hpp new file mode 100644 index 0000000..f9f4d87 --- /dev/null +++ b/include/vls/modules/ArtifactCache.hpp @@ -0,0 +1,83 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::modules { + +// Identity of one private module artifact. Compatibility covers frontend, +// target ABI, stdlib and flags; context names the producer; inputs binds the +// exact command, source and textual closure; kind distinguishes CMI/object. +struct ArtifactKey { + std::string compatibility, context, inputs, kind; + auto operator<=>(const ArtifactKey &) const = default; + [[nodiscard]] std::string identity() const; +}; + +struct ArtifactEntry { + ArtifactKey key; + std::filesystem::path path; + std::string sha256; +}; + +// An immutable, completely published generation. Readers retain it while +// eviction removes only generations no reader references. +class ArtifactGeneration { + public: + [[nodiscard]] const std::string &id() const noexcept { return id_; } + [[nodiscard]] const std::filesystem::path &root() const noexcept { return root_; } + [[nodiscard]] std::optional find(const ArtifactKey &key) const; + + private: + friend class ArtifactCache; + ArtifactGeneration(std::string id, std::filesystem::path root, + std::map entries) + : id_(std::move(id)), root_(std::move(root)), entries_(std::move(entries)) {} + std::string id_; + std::filesystem::path root_; + std::map entries_; +}; + +// Private artifact cache. Publication is all-or-nothing and content addressed; +// a failed publication leaves no generation behind. +class ArtifactCache { + public: + explicit ArtifactCache(std::filesystem::path root, std::size_t retained = 2); + ~ArtifactCache(); + ArtifactCache(const ArtifactCache &) = delete; + ArtifactCache &operator=(const ArtifactCache &) = delete; + + [[nodiscard]] std::expected, std::string> + publish(const std::map &artifacts); + [[nodiscard]] std::shared_ptr current() const; + // Removes unreferenced generations beyond the retained limit. + std::size_t collect(); + [[nodiscard]] std::size_t generations() const; + + private: + struct State; + std::shared_ptr state_; +}; + +// Produces one artifact per planned unit in dependency order. Any failure or +// cancellation removes the staging directory and publishes nothing. +using ArtifactWork = std::function( + std::stop_token, const Build::ContextKey &, const std::filesystem::path &output)>; + +[[nodiscard]] std::expected, std::string> +produce_module_artifacts(const ModulePlan &plan, ArtifactCache &cache, + const std::filesystem::path &staging, ArtifactWork work, + std::stop_token stop = std::stop_token{}); + +} // namespace vls::modules diff --git a/include/vls/modules/GccArtifacts.hpp b/include/vls/modules/GccArtifacts.hpp new file mode 100644 index 0000000..bf65281 --- /dev/null +++ b/include/vls/modules/GccArtifacts.hpp @@ -0,0 +1,39 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::modules { + +struct ModuleCommand { + std::filesystem::path working_directory; + // Absolute compiler path first. Arguments must not depend on the caller's + // working directory: the work runs in a private directory. + std::vector arguments; +}; + +using ModuleCommandLookup = std::function(const Build::ContextKey &)>; + +struct GccArtifactOptions { + std::chrono::milliseconds deadline{60000}; + std::size_t max_output_bytes{64 * 1024 * 1024}; + std::size_t max_artifact_bytes{512 * 1024 * 1024}; +}; + +// Real GCC module artifact production for one planned unit: runs the looked-up +// command in a private working directory with a private module cache, requires +// exactly one verified CMI and copies it to `output`. Tool authority, the +// command's environment and its provenance are the caller's responsibility. +[[nodiscard]] ArtifactWork +gcc_module_artifact_work(ModuleCommandLookup lookup, + GccArtifactOptions options = GccArtifactOptions{}); + +} // namespace vls::modules diff --git a/include/vls/modules/GccScan.hpp b/include/vls/modules/GccScan.hpp new file mode 100644 index 0000000..25b1973 --- /dev/null +++ b/include/vls/modules/GccScan.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::modules { + +struct ScanCommand { + std::filesystem::path working_directory; + // Absolute compiler first. Must contain exactly one absolute -fdeps-file=. + std::vector arguments; + ExpectedOutput output; +}; + +using ScanCommandLookup = std::function(const Build::ContextKey &)>; + +struct ScanProduct { + std::string p1689; + std::optional rule; +}; + +struct ScanOptions { + std::filesystem::path directory; // private output directory + std::chrono::milliseconds deadline{60000}; + std::size_t max_bytes{max_scan_bytes}; +}; + +// Runs one checked P1689 scan command and decodes its dependency file. The +// product is filled only on success; a failure throws so the scheduler records +// a failed task. No compiler option comes from project metadata here. +[[nodiscard]] std::function +gcc_module_scan_work(ScanCommandLookup lookup, Build::ContextKey context, + std::shared_ptr product, ScanOptions options = ScanOptions{}); + +} // namespace vls::modules diff --git a/include/vls/modules/ModuleGraph.hpp b/include/vls/modules/ModuleGraph.hpp new file mode 100644 index 0000000..c4a61e0 --- /dev/null +++ b/include/vls/modules/ModuleGraph.hpp @@ -0,0 +1,227 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::modules { + +namespace Build = Void::LanguageServer::Build; + +inline constexpr std::size_t max_scan_bytes = 256 * 1024, max_scan_depth = 16; +inline constexpr std::size_t max_field_bytes = 4096, max_rule_items = 512; +inline constexpr std::size_t max_units = 4096, max_graph_items = 32768; +inline constexpr std::size_t max_graph_bytes = 16 * 1024 * 1024; + +struct ExpectedOutput { + std::filesystem::path working_directory; + std::string spelling; + bool operator==(const ExpectedOutput &other) const { + return working_directory.native() == other.working_directory.native() && + spelling == other.spelling; + } +}; + +enum class LookupMethod { by_name, include_angle, include_quote }; +struct ModuleDescription { + std::string logical_name; + std::optional source_path, compiled_module_path; + bool unique_on_source_path{}; + auto operator<=>(const ModuleDescription &) const = default; +}; +struct ProvidedModule : ModuleDescription { + bool is_interface{true}; + auto operator<=>(const ProvidedModule &) const = default; +}; +struct RequiredModule : ModuleDescription { + LookupMethod lookup{LookupMethod::by_name}; + auto operator<=>(const RequiredModule &) const = default; +}; + +enum class ScanError { + invalid_json, + invalid_shape, + unsupported_version, + unsupported_field, + invalid_invocation, + wrong_directory, + wrong_output, + limit +}; + +// GCC 16.2 single-rule version 0, revision 0. Only the decoder constructs rules. +class ScanRule { + public: + const ExpectedOutput &output() const { return output_; } + const auto &additional_outputs() const { return additional_outputs_; } + const auto &provides() const { return provides_; } + const auto &requirements() const { return requirements_; } + std::size_t wire_bytes() const { return wire_bytes_; } + + private: + friend std::expected decode_scan(std::string_view, const ExpectedOutput &); + ScanRule() = default; + ExpectedOutput output_; + std::vector additional_outputs_; + std::vector provides_; + std::vector requirements_; + std::size_t wire_bytes_{}; +}; +using ScanResult = std::expected; +[[nodiscard]] ScanResult decode_scan(std::string_view bytes, const ExpectedOutput &expected); + +// The input owner admits this compatible set. Compatibility identifies frontend, target ABI, +// stdlib, flags/environment affecting module interchange. Lookup covers all ordered search +// roots, including misses, shadowing, overlays and generated inputs. +struct ModuleDomain { + Build::Generation generation; + std::string compatibility, lookup; + bool operator==(const ModuleDomain &) const = default; +}; + +// Collision-checked identities for the exact invocation, owning source and immutable transitive +// inputs. textual_closure includes header contents behind staged imports and their relevant +// artifact generations. A user-only depfile additionally needs independently sealed system inputs. +struct UnitInputs { + std::string command, source, textual_closure; + std::optional system_closure; + bool operator==(const UnitInputs &) const = default; +}; + +// Provenance from staging an immutable header CMI. The scanner separately identifies the +// generation it actually consumed. source_identity names the resolved header across spellings. +struct StagedHeader { + std::string generation, source_identity; + ModuleDomain domain; + Build::ContextKey producer; + UnitInputs inputs; + bool operator==(const StagedHeader &) const = default; +}; + +struct CensusMember { + Build::ContextKey context; + ExpectedOutput output; + UnitInputs inputs; + // Changes on scanner replacement, even for equal source/command or a formerly absent rule. + std::string scan_revision; + std::optional staged_header; + bool operator==(const CensusMember &) const = default; +}; +struct ModuleCensus { + ModuleDomain domain; + std::string revision; + bool closed{}; + // All eligible commands in this dependency domain. Other BuildGeneration alternatives + // remain invisible. Distinct visibility sets require distinct censuses. + std::vector members; +}; + +enum class ScanMethod { unknown, preprocess_md, preprocess_mmd, missing_allowed }; +enum class UnitKind { + unknown, + ordinary, + implementation, + primary_interface, + interface_partition, + internal_partition, + header_unit +}; +struct HeaderProvision { + std::size_t index{}; // Index in ScanRule::provides(). + std::string source_identity; +}; +struct HeaderUse { + std::size_t index{}; // Index in ScanRule::requirements(). + std::string source_identity; + std::optional loaded_generation; +}; +struct ScanEvidence { + ModuleDomain domain; + Build::ContextKey context; + UnitInputs inputs; + std::string scan_revision; + std::optional exit_status; + std::optional rule; + ScanMethod method{ScanMethod::unknown}; + // The owner proves a complete pass under these inputs (including generated inputs) and + // classifies every header-unit provision from its actual invocation and resolved source. + bool complete{}; + // Implementation and ordinary importer can have identical rules. Only independent frontend + // evidence can set one of these two kinds on an import-only TU. + UnitKind import_only_kind{UnitKind::unknown}; + std::vector provided_headers; + // Engaged empty means the owner positively established absence of header-unit imports. + // Bindings attest every reported lookup/source spelling to the resolved source identity. + std::optional> header_uses; + // Verified writer identities in primary-output, then additional_outputs() order. An + // isolated invocation can bind the same spelling to a different private destination. + std::vector writers; +}; + +enum class PlanIssue { + incomplete_census, + invalid_context, + wrong_domain, + duplicate_member, + missing_scan, + duplicate_scan, + scan_failed, + missing_rule, + invalid_rule, + stale_scan, + missing_source, + incomplete_inputs, + incomplete_scan, + unproven_mapping, + missing_provider, + duplicate_provider, + stale_header, + writer_collision, + cycle, + limit +}; +struct Blocker { + PlanIssue code{}; + std::optional unit; // Index in ModulePlan::units, when available. + std::string detail; + std::optional scan_error; + auto operator<=>(const Blocker &) const = default; +}; +struct PlannedUnit { + CensusMember member; + UnitKind kind{UnitKind::unknown}; + // Indices in ModulePlan::units. These are direct consumers across the admitted census. + std::vector consumers; +}; +struct ModulePlan { + ModuleDomain domain; + std::string census_revision; + std::vector units; // Ascending ContextKey order. + // Prerequisites first, requested TU last. Failure leaves the order empty. + std::vector order; + std::vector blockers; + // All eligible scans can establish provider claims. A complete census may still have + // missing imports, duplicate providers, conflicting writers or cycles. Unproven claims + // withhold unit kinds and reverse edges. + bool claims_complete{}; + [[nodiscard]] bool ready() const { + return claims_complete && !order.empty() && blockers.empty(); + } + // Also checks non-reachable members. A renamed or newly visible provider can change a + // previous successful or missing lookup without having had any positive reverse edge. + [[nodiscard]] bool matches_census(const ModuleCensus ¤t) const; +}; + +[[nodiscard]] ModulePlan build_module_plan(const ModuleCensus &census, + std::span scans, + const Build::ContextKey &requested); + +} // namespace vls::modules diff --git a/include/vls/modules/ModuleWorkQueue.hpp b/include/vls/modules/ModuleWorkQueue.hpp new file mode 100644 index 0000000..711a3db --- /dev/null +++ b/include/vls/modules/ModuleWorkQueue.hpp @@ -0,0 +1,57 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +namespace vls::modules { + +enum class ModuleWorkKind { scan, artifact }; + +struct ModuleTaskResult { + std::string document; + ModuleWorkKind kind{ModuleWorkKind::scan}; + std::uint64_t revision{}; + scheduler::Outcome outcome{scheduler::Outcome::failed}; + std::string detail; +}; + +using ModuleWork = std::function; + +// Editor-facing module work admission on the shared bounded scheduler. +// Scans run at background priority and artifact preparation at artifact +// priority, so neither delays foreground editor requests. A newer revision of +// one kind supersedes queued work and cancels running work; closing or editing +// a document cancels both kinds. +class ModuleWorkQueue { + public: + explicit ModuleWorkQueue(scheduler::Scheduler &scheduler); + ModuleWorkQueue(const ModuleWorkQueue &) = delete; + ModuleWorkQueue &operator=(const ModuleWorkQueue &) = delete; + + // False for a stale revision, an empty key or a refused scheduler admission. + [[nodiscard]] bool submit( + std::string document, ModuleWorkKind kind, std::uint64_t revision, ModuleWork work, + std::function completion = std::function{}); + void cancel(std::string_view document); + void cancel_all(); + + struct Counts { + std::uint64_t submitted{}, completed{}, cancelled{}, failed{}; + }; + [[nodiscard]] Counts counts() const; + + private: + [[nodiscard]] static std::string key(std::string_view document, ModuleWorkKind kind); + scheduler::Scheduler &scheduler_; + mutable std::mutex mutex_; + std::map revisions_[2]; + Counts counts_; +}; + +} // namespace vls::modules diff --git a/include/vls/modules/ScanCommand.hpp b/include/vls/modules/ScanCommand.hpp new file mode 100644 index 0000000..537f5a8 --- /dev/null +++ b/include/vls/modules/ScanCommand.hpp @@ -0,0 +1,34 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace vls::modules { + +enum class ScanCommandError { + invalid_context, + missing_source, + duplicate_source, + relative_dependency_file, + limit +}; + +struct ScanInvocation { + // Driver first, then the original checked arguments with the scan options + // appended. The owning source is the final operand. + std::vector arguments; +}; + +// Derives a P1689 scan command from a checked compiler context. The driver and +// owning source come from the context itself; the dependency file must be +// absolute. Existing output, preprocess and dependency options are removed so +// project metadata cannot select or duplicate the scan outputs. +[[nodiscard]] std::expected +build_scan_invocation(const Build::BuildContext &context, const ExpectedOutput &output, + const std::filesystem::path &dependency_file); + +} // namespace vls::modules diff --git a/include/vls/modules/ScheduledArtifacts.hpp b/include/vls/modules/ScheduledArtifacts.hpp new file mode 100644 index 0000000..18cfebc --- /dev/null +++ b/include/vls/modules/ScheduledArtifacts.hpp @@ -0,0 +1,23 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace vls::modules { + +// Produces the planned units in dependency order through the shared scheduler +// at artifact priority. A superseded, cancelled, timed-out or failed unit +// publishes nothing; the staging directory is always removed. +[[nodiscard]] std::expected, std::string> +produce_module_artifacts_scheduled(const ModulePlan &plan, ArtifactCache &cache, + const std::filesystem::path &staging, ArtifactWork work, + scheduler::Scheduler &scheduler, + std::stop_token stop = std::stop_token{}); + +} // namespace vls::modules diff --git a/include/vls/navigation/Navigation.hpp b/include/vls/navigation/Navigation.hpp new file mode 100644 index 0000000..e72898c --- /dev/null +++ b/include/vls/navigation/Navigation.hpp @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::navigation { + +struct Position { + std::uint32_t line{}, character{}; + auto operator<=>(const Position &) const = default; +}; +struct Range { + Position start, end; + auto operator<=>(const Range &) const = default; +}; +struct Location { + std::string path; + Range range; + auto operator<=>(const Location &) const = default; +}; + +// Semantic identity of one binding. The definition location joins equal +// symbols across analysis contexts; the name distinguishes unrelated symbols +// without a proven definition. +struct Binding { + std::string name; + std::optional definition; + auto operator<=>(const Binding &) const = default; +}; + +struct Fact { + Binding binding; + std::string context; + std::string source; // use file + std::string content; // content identity of the observed source + Range use; + bool editable{}; + std::string provenance; +}; + +struct ContextState { + std::string context; + bool complete{}; + std::string reason; +}; + +struct FactSet { + std::string backend; + std::uint64_t generation{}; + std::vector facts; + std::vector contexts; + std::map current_sources; // path -> current content +}; + +enum class Refusal { + none, + unknown_binding, + ambiguous_binding, + incomplete_coverage, + stale_source, + non_editable_origin, + generated_name, + invalid_name, + unchanged_name, + multi_file_without_transaction, +}; + +struct References { + std::vector locations; + bool coverage_complete{}; + std::vector incomplete_contexts; + bool truncated{}; +}; + +struct Edit { + std::string path; + Range range; + std::string replacement; + std::string content; // content identity the edit was prepared against +}; + +struct RenamePlan { + Refusal refusal{Refusal::none}; + std::string detail; + std::vector edits; + [[nodiscard]] bool ready() const { return refusal == Refusal::none && !edits.empty(); } +}; + +// Resolves the unique binding at a position. Overlapping distinct bindings are +// ambiguous and never resolved by iteration order. +[[nodiscard]] std::expected binding_at(const FactSet &, std::string_view path, + Position); + +// All proven uses. Partial locations are retained for diagnosis, but +// coverage_complete is false whenever any context is incomplete. +[[nodiscard]] References references(const FactSet &, const Binding &, std::size_t limit = 512); + +// Only a ready plan may be applied. Refusals are explicit for incomplete +// coverage, stale sources, non-editable origins, ambiguous bindings, +// generated/invalid names and multi-file edits without a transactional client. +[[nodiscard]] RenamePlan prepare_rename(const FactSet &, std::string_view path, Position, + std::string_view replacement, bool transactional_client); + +} // namespace vls::navigation diff --git a/include/vls/reflection/Provenance.hpp b/include/vls/reflection/Provenance.hpp new file mode 100644 index 0000000..71186f5 --- /dev/null +++ b/include/vls/reflection/Provenance.hpp @@ -0,0 +1,243 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::reflection { + +// Version of the provenance/value snapshot schema. Derived index and trace +// renderers must reject an incompatible version rather than reinterpret it. +inline constexpr std::uint32_t schema_version = 1; + +// Canonical, context-qualified semantic identity of one reflected or generated +// entity. It is assigned by the extractor from compiler state; this library +// never invents an identity from a source string. +using EntityId = std::string; + +struct Range { + std::string path; + std::uint32_t line{}, character{}, endLine{}, endCharacter{}; + auto operator<=>(const Range &) const = default; +}; + +// What one link of a provenance chain represents. A spelling is an editable +// token; expansion and splice sites are the generated constructs that produced +// a token; a reflected declaration is the original entity behind a splice; a +// synthesized entity has no editable spelling at all. +enum class OriginKind { + spelling, + expansion, + splice, + reflected_declaration, + synthesized, +}; + +struct Origin { + OriginKind kind{OriginKind::synthesized}; + std::optional range; // absent when the compiler gave no location + std::optional entity; // reflected or generated entity identity + std::string note; // proposal/facility or instantiation context + auto operator<=>(const Origin &) const = default; +}; + +// Innermost origin first. A generated entity can stay navigable through the +// chain while remaining non-editable: generated names without a reliable +// editable origin are never automatically renameable. +struct Provenance { + std::vector origins; + bool gap{}; // at least one link in the chain is unavailable + std::string context; // snapshot/instantiation identity + + [[nodiscard]] bool navigable() const; // some origin carries a real range + [[nodiscard]] bool editable() const; // complete chain rooted at a spelling + auto operator<=>(const Provenance &) const = default; +}; + +enum class ValueKind { + integral, + text, + boolean, + entity, + opaque, // a real value the compiler cannot render; text is the reason + unavailable, // the value could not be obtained; text is the reason +}; + +struct Value { + ValueKind kind{ValueKind::unavailable}; + std::int64_t integral{}; + bool boolean{}; + std::string text; // text value, or the reason for opaque/unavailable + std::string type; // canonical type spelling when the compiler provides it + EntityId entity; // referenced entity when kind is entity + auto operator<=>(const Value &) const = default; +}; + +struct Member { + std::string name; + Value value; + auto operator<=>(const Member &) const = default; +}; + +// One real reflected or synthesized entity. Members may reference other +// entities; expansion resolves those references lazily and boundedly. +struct Entity { + EntityId id; + std::string name; + std::string type; + std::vector members; + Provenance provenance; + bool synthesized{}; + auto operator<=>(const Entity &) const = default; +}; + +struct Limits { + std::size_t entities{4096}; + std::size_t membersPerEntity{64}; + std::size_t originsPerProvenance{16}; + std::size_t nameBytes{256}; + std::size_t typeBytes{1024}; + std::size_t textBytes{4096}; + std::size_t contextBytes{1024}; + std::size_t snapshotBytes{8 * 1024 * 1024}; + std::size_t expansionDepth{8}; + std::size_t expansionValues{1024}; + std::size_t capabilities{256}; +}; + +// Flattened, depth-first expansion of one entity. Cycles and limit cuts are +// explicit paths, never silently omitted values. +struct Expansion { + struct Entry { + std::string path; // member path from the root, e.g. "outer.inner" + std::size_t depth{}; + ValueKind kind{ValueKind::unavailable}; + std::string type; + std::string text; + EntityId entity; + std::optional link; // source range of the referenced entity + auto operator<=>(const Entry &) const = default; + }; + std::vector entries; + std::vector cycles; // repeated entity on the current path + std::vector truncated; // cut by depth or value count + [[nodiscard]] bool complete() const { return cycles.empty() && truncated.empty(); } +}; + +// One explanation line of a virtual generated view. A line is a semantic +// explanation, never compilable text: it may be indented prose with a source +// link, and consumers must never feed it back to a compiler. +struct VirtualLine { + std::string text; + std::size_t depth{}; + std::optional link; + auto operator<=>(const VirtualLine &) const = default; +}; + +struct VirtualView { + std::vector lines; + bool truncated{}; + // Virtual generated views are read-only explanations by construction. + [[nodiscard]] bool compilable() const { return false; } +}; + +// LSP-shaped hover for one entity: a semantic explanation plus the source +// links it explains. The markup is Markdown but never compilable text. +struct Hover { + std::string markup; + std::optional range; + auto operator<=>(const Hover &) const = default; +}; + +// Navigation targets in provenance-chain order, deduplicated and bounded. +// A generated entity stays navigable through the chain that produced it. +[[nodiscard]] std::vector locations(const Provenance &, std::size_t limit = 16); + +// Renders one entity and its bounded expansion as a read-only semantic +// explanation with source links. Cycles, truncation and opaque values stay +// explicit; the result is never compilable text. +[[nodiscard]] VirtualView render(const Entity &, const Expansion &, const Limits & = Limits{}); + +// LSP-shaped hover markup for one entity and its expansion, with the entity's +// first source range. The markup lists the virtual view and its source links. +[[nodiscard]] Hover hover(const Entity &, const Expansion &, const Limits & = Limits{}); + +// Bounded snapshot of one analysis generation. Serialization is versioned and +// every consumer validates its own limits before trusting the bytes. +class Snapshot { + public: + explicit Snapshot(Limits = Limits{}); + + // Rejects duplicates, oversized strings, too many entities or members. + [[nodiscard]] bool add(Entity); + [[nodiscard]] bool contains(const EntityId &) const; + [[nodiscard]] const Entity *find(const EntityId &) const; + [[nodiscard]] const std::vector &entities() const noexcept; + [[nodiscard]] std::size_t size() const; + [[nodiscard]] const Limits &limits() const noexcept; + + // Depth-first expansion of one entity. Unknown identities are an error. + [[nodiscard]] std::expected + expand(const EntityId &, std::optional depth = std::nullopt) const; + + [[nodiscard]] std::expected serialize() const; + [[nodiscard]] static std::expected parse(std::string_view, + Limits = Limits{}); + + private: + Limits limits_; + std::vector entities_; +}; + +// Proposal/facility support declared by the accepted backend. An unknown entry +// is an explicit capability error; it never falls back to a lexical answer. +struct Capability { + std::string proposal; // e.g. "P2996" + std::string facility; // e.g. "splices" + bool supported{}; + std::string reason; // required when unsupported + auto operator<=>(const Capability &) const = default; +}; + +class Capabilities { + public: + explicit Capabilities(Limits = Limits{}); + + // Rejects duplicates, oversized fields and an unsupported entry without a + // reason. + [[nodiscard]] bool add(Capability); + [[nodiscard]] std::expected query(std::string_view proposal, + std::string_view facility) const; + [[nodiscard]] std::size_t size() const; + + private: + Limits limits_; + std::vector entries_; +}; + +// One splice origin reported by the compiler: the splice site and the entity +// it designates. Columns are 1-based UTF-8 byte offsets. The compiler reports +// a start coordinate only, so ranges are zero-width until an end is available. +struct SpliceOrigin { + std::string source; + std::uint32_t line{}, byteColumn{}; + std::string targetKind; // "declaration", "type" or "value" + std::string targetName; + std::string targetSource; + std::optional targetLine, targetByteColumn; +}; + +// Composes entities from compiler-reported splice origins. Identity is +// composed from the reported target kind, name and declaration location; the +// provenance chain is the splice site followed by the reflected declaration, +// or an explicit gap when the compiler reported no target location. The first +// chain for an identity wins and the result stays within the snapshot limits. +[[nodiscard]] Snapshot snapshot_from_splices(std::span, Limits = Limits{}); + +} // namespace vls::reflection diff --git a/include/vls/scheduler/Scheduler.hpp b/include/vls/scheduler/Scheduler.hpp new file mode 100644 index 0000000..0b21790 --- /dev/null +++ b/include/vls/scheduler/Scheduler.hpp @@ -0,0 +1,82 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::scheduler { + +enum class Priority { artifact = 0, background = 1, foreground = 2 }; + +struct Budget { + std::size_t foreground{4}; + std::size_t background{2}; + std::size_t artifact{1}; + std::size_t queued{64}; + std::size_t memory_mib{1024}; + std::chrono::milliseconds watchdog{30000}; + + [[nodiscard]] bool valid() const noexcept; +}; + +enum class Outcome { completed, failed, cancelled, timed_out }; + +struct Estimate { + Priority priority{Priority::background}; + std::string key; + std::uint64_t revision{}; + std::size_t memory_mib{}; +}; + +struct Result { + std::string key; + std::uint64_t revision{}; + Outcome outcome{Outcome::failed}; + std::string detail; +}; + +struct Metrics { + std::uint64_t accepted{}, completed{}, failed{}, cancelled{}, timed_out{}, rejected{}; + std::size_t queued_peak{}, running_peak{}, running_memory_peak{}; + std::uint64_t queue_nanoseconds{}, run_nanoseconds{}; +}; + +// Work returns a detail string on success or throws on failure. It must honor +// the stop token so cancellation and the running watchdog stay bounded. +using Work = std::function; +using Completion = std::function; + +// Bounded, priority-separated executor. Foreground, background and artifact +// pools have reserved capacity, so a saturated background queue never delays a +// foreground request. Every accepted submission receives exactly one terminal +// completion; a refused submission receives none and returns false. +class Scheduler { + public: + explicit Scheduler(Budget = Budget{}); + ~Scheduler(); + Scheduler(const Scheduler &) = delete; + Scheduler &operator=(const Scheduler &) = delete; + Scheduler(Scheduler &&) = delete; + Scheduler &operator=(Scheduler &&) = delete; + + // A newer revision of the same key supersedes queued work immediately and + // requests cooperative cancellation of running work. + [[nodiscard]] bool submit(Estimate, Work, Completion); + void cancel(std::string_view key); + void cancel_all(); + // Waits until every accepted submission has reached a terminal result. + void drain(); + [[nodiscard]] Metrics metrics() const; + [[nodiscard]] const Budget &budget() const noexcept; + + private: + struct State; + std::unique_ptr state_; +}; + +} // namespace vls::scheduler diff --git a/include/vls/semantic/Diagnostics.hpp b/include/vls/semantic/Diagnostics.hpp new file mode 100644 index 0000000..174bd3c --- /dev/null +++ b/include/vls/semantic/Diagnostics.hpp @@ -0,0 +1,109 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::semantic { +namespace Documents = Void::LanguageServer::Documents; +using DiagnosticSnapshot = std::shared_ptr; + +// GCC can emit literal filenames, including percent signs. These spellings are +// supplied by the launcher and are compared exactly, without URL decoding. +struct ArtifactName { + std::string uri, base_uri; + auto operator<=>(const ArtifactName &) const = default; +}; +struct DiagnosticArtifact { + ArtifactName name; + DiagnosticSnapshot snapshot; +}; +struct ReportedRegion { + std::uint32_t first_line, first_column, last_line, end_column; +}; +enum class ColumnUnit { ascii_consensus, utf8_bytes, gcc_display }; +enum class FirstLineBom { unknown, counted, skipped }; +struct CoordinatePolicy { + ColumnUnit unit{ColumnUnit::ascii_consensus}; + unsigned tabstop{8}; + FirstLineBom bom{FirstLineBom::unknown}; +}; +struct LocationRequest { + const DiagnosticArtifact &artifact; + ReportedRegion region; + std::size_t result_index, location_index; + bool related; +}; + +struct DiagnosticJob { + std::string invocation_id, input_view_id; + DiagnosticSnapshot owner; + std::vector artifacts; + // The input owner accounts for unresolved includes and lookup dependencies. + bool inputs_complete{}; + // Return a policy only for a proven physical location in the immutable + // inputs. A matching snippet cannot establish the origin of a #line remap. + std::function(const LocationRequest &)> physical_origin; +}; +struct DiagnosticOutput { + std::string_view invocation_id, input_view_id; + std::optional exit_code; + bool stream_complete{}; + std::string_view sarif; +}; +enum class DiagnosticError { + invalid_job, + wrong_capture, + incomplete_stream, + failed_process, + malformed_report, + unsupported_report, + wrong_owner, + tool_failure, + resource_limit +}; +enum class LocationGap { + none, + no_location, + unknown_artifact, + artifact_mismatch, + incomplete_region, + unproven_origin, + ambiguous_column +}; +struct DiagnosticLocation { + LocationGap gap{LocationGap::no_location}; + DiagnosticSnapshot snapshot; + std::optional range; +}; +struct RelatedLocation { + std::string message; + DiagnosticLocation location; +}; +enum class DiagnosticSeverity { error, warning, information, hint }; +struct CompilerDiagnostic { + DiagnosticSeverity severity; + std::string message, rule; + DiagnosticLocation location; + std::vector related; +}; +struct DiagnosticBatch { + std::string invocation_id, input_view_id; + DiagnosticSnapshot owner; + std::vector diagnostics; + // The publisher must still validate that this invocation is current. + bool complete_for_owner{}; +}; + +[[nodiscard]] std::expected +decode_gcc_diagnostics(const DiagnosticJob &, const DiagnosticOutput &); +} // namespace vls::semantic diff --git a/include/vls/semantic/EditorDiagnostics.hpp b/include/vls/semantic/EditorDiagnostics.hpp new file mode 100644 index 0000000..10a9089 --- /dev/null +++ b/include/vls/semantic/EditorDiagnostics.hpp @@ -0,0 +1,65 @@ +#pragma once + +#include + +#include + +namespace vls::semantic { + +// The input thread brackets document and workspace transitions. The analysis worker +// publishes through the same ordered output queue as request responses. +class EditorDiagnostics { + public: + using Send = std::function; + EditorDiagnostics(const std::filesystem::path &root, std::shared_ptr, + WorkspaceSession &, const Documents::DocumentStore &, Send); + ~EditorDiagnostics(); + void set_version_support(bool); + void begin_update(); + void finish_update(bool workspace_changed = false); + void stop(); + [[nodiscard]] Void::LanguageServer::Protocol::Json status(std::string_view uri) const; + [[nodiscard]] bool supports_occurrences() const noexcept; + // Bounded workspace symbol search over the context-aware index. + [[nodiscard]] Void::LanguageServer::Protocol::Json + workspace_symbols(std::string_view query) const; + // Index-backed completion for the identifier prefix before the position. + // Items are explicitly marked incomplete until compiler-native completion + // exists; visibility is not proven by the index. + [[nodiscard]] Void::LanguageServer::Protocol::Json + completion(std::string_view uri, Documents::Position position) const; + // Compiler-provided call signature at the position, or null when no + // verified occurrence carries one. + [[nodiscard]] Void::LanguageServer::Protocol::Json + signature_help(std::string_view uri, Documents::Position position) const; + // Deferred completion detail. The item's data carries the captured + // identity and index generation; a changed generation returns the item + // without details rather than details for a different entity. + [[nodiscard]] Void::LanguageServer::Protocol::Json + completion_resolve(const Void::LanguageServer::Protocol::Json &item) const; + + struct NavigationReply { + Void::LanguageServer::Protocol::Json result; + std::optional refusal; + }; + // A refusal means the answer would be incomplete or unsafe; the result is + // retained for diagnosis but must not be presented as complete. + [[nodiscard]] NavigationReply references(std::string_view uri, + Documents::Position position) const; + [[nodiscard]] NavigationReply prepare_rename(std::string_view uri, + Documents::Position position) const; + [[nodiscard]] NavigationReply rename(std::string_view uri, Documents::Position position, + std::string_view replacement) const; + void set_transactional_rename(bool supported); + // Answers are null when no verified occurrence covers the requested position. + [[nodiscard]] Void::LanguageServer::Protocol::Json hover(std::string_view uri, + Documents::Position position) const; + [[nodiscard]] Void::LanguageServer::Protocol::Json + definition(std::string_view uri, Documents::Position position) const; + + private: + struct State; + std::unique_ptr state_; +}; + +} // namespace vls::semantic diff --git a/include/vls/semantic/Occurrences.hpp b/include/vls/semantic/Occurrences.hpp new file mode 100644 index 0000000..78219a4 --- /dev/null +++ b/include/vls/semantic/Occurrences.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace vls::semantic { + +// A compiler-owned direct-call fact. Byte spans from the stock observer are +// already converted to the captured snapshot's negotiated character positions. +struct Occurrence { + std::string name, type, canonical_type, signature; + DiagnosticSnapshot use_file; + Documents::Range use; + DiagnosticSnapshot definition_file; + Documents::Range definition; + + [[nodiscard]] bool has_definition() const noexcept { return definition_file != nullptr; } +}; + +struct OccurrenceReport { + std::vector occurrences; + bool complete{}; + bool partial{}; + std::string reason; +}; + +enum class OccurrenceError { invalid_report, wrong_nonce }; + +// Decode a stock-observer report against the exact capture that was compiled. +// Unknown paths, byte spans that do not match the captured bytes, duplicates +// and malformed envelopes reject the whole report. +[[nodiscard]] std::expected +decode_occurrences(std::string_view report, std::string_view nonce, + std::span capture); + +} // namespace vls::semantic diff --git a/include/vls/semantic/SourceCatalog.hpp b/include/vls/semantic/SourceCatalog.hpp new file mode 100644 index 0000000..a964317 --- /dev/null +++ b/include/vls/semantic/SourceCatalog.hpp @@ -0,0 +1,118 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::semantic { +namespace Documents = Void::LanguageServer::Documents; + +struct SourceScope { + Void::LanguageServer::Build::WorkspaceIdentity workspace; + std::uint64_t configuration, trust; + bool operator==(const SourceScope &) const = default; +}; + +enum class SourceIssue { + wrong_authority, + invalid_path, + outside_scope, + unsupported_route, + conflicting_names, + missing, + missing_parent, + not_regular, + hard_link, + unavailable, + unavailable_overlay, + invalid_text, + changed, + resource_limit +}; + +struct SourceError { + SourceIssue issue; + std::filesystem::path path; +}; + +struct SourceRequest { + std::filesystem::path path; + bool allow_missing{}; + // Observe a file, directory or missing route without opening file payloads. + bool lookup_only{}; +}; + +struct SourceLimits { + std::size_t files{1024}; + std::size_t name_bytes{512 * 1024}; + std::size_t file_bytes{16 * 1024 * 1024}; + std::size_t total_bytes{32 * 1024 * 1024}; + std::size_t descriptors{256}; +}; + +enum class SourceNode { missing, directory, regular }; +struct CapturedSource { + std::filesystem::path logical_path; + // Content requests retain the selected snapshot. Lookup-only requests retain the node kind. + std::shared_ptr snapshot; + SourceNode node{SourceNode::missing}; + // GCC's __TIMESTAMP__ depends on the input file's modification time in seconds. + std::optional modified_at{}; +}; + +struct SourceGrant; +using InstalledSourceGrant = std::shared_ptr; +struct SourceEvidence; +struct SourceAccounting; + +class SourceCapture { + public: + SourceCapture(const SourceCapture &) = delete; + [[nodiscard]] std::span entries() const noexcept { return entries_; } + + private: + friend class SourceCatalog; + explicit SourceCapture(std::shared_ptr evidence); + std::shared_ptr evidence_; + std::vector entries_; +}; + +// The workspace owner installs only its explicitly authorized source directories. +// Captures witness the requested names. A worker must separately establish lookup closure. +class SourceCatalog { + public: + // The owning session keeps its document store alive for the catalog's lifetime. + explicit SourceCatalog(const Documents::DocumentStore &documents, + std::function before_capture_validation = {}); + [[nodiscard]] std::expected + install(const SourceScope &scope, std::span directories); + void revoke(); + + [[nodiscard]] std::expected, SourceError> + capture(const SourceScope &job, const InstalledSourceGrant &grant, + const Documents::FileOverlayInventory &census, std::span requests, + SourceLimits limits = {}) const; + + [[nodiscard]] std::expected validate(const SourceScope &job, + const SourceCapture &capture) const; + + private: + const Documents::DocumentStore &documents_; + std::mutex installations_; + std::atomic installed_; + std::shared_ptr accounting_; + std::function before_capture_validation_; +}; + +} // namespace vls::semantic diff --git a/include/vls/semantic/StockCompiler.hpp b/include/vls/semantic/StockCompiler.hpp new file mode 100644 index 0000000..19f00b0 --- /dev/null +++ b/include/vls/semantic/StockCompiler.hpp @@ -0,0 +1,79 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::semantic { + +class GccProfile { + public: + // Only the launcher selects this file for its explicitly selected workspace. + static std::expected, std::string> + load(const std::filesystem::path &file); + // Prepares the profile in process from the selected GCC driver. No + // external script or pre-generated JSON is required. + static std::expected, std::string> + prepare(const std::filesystem::path &driver); + std::filesystem::path driver, frontend, bubblewrap, strace, prlimit; + std::vector mounts; + // Optional launcher-selected occurrence observer. Its exact bytes are + // re-verified for every job; metadata cannot select or alter it. + std::filesystem::path observer; + std::string observer_identity; + std::string target, flags, identity; + + [[nodiscard]] bool observes() const noexcept { return !observer.empty(); } + + private: + GccProfile() = default; +}; + +struct StockAnalysis { + DiagnosticBatch batch; + std::shared_ptr sources; + Void::LanguageServer::Build::Revision revision; + // Present only when the launcher-selected observer produced a verified report. + std::optional occurrences; + // Why occurrence facts are unavailable when the observer was selected. + std::string occurrence_detail; + // Hints for the next run. Each new job reacquires and verifies all positive and negative + // inputs. + std::vector lookups; + std::size_t compiler_runs{}; + std::optional unproven_location_origin; +}; + +// One job owns an isolated filesystem and runs the regular GCC frontend. Caller revalidates +// the lease and capture before delivering diagnostics to an editor. +[[nodiscard]] std::expected +analyze_with_gcc(const GccProfile &profile, const SemanticContextLease &lease, + const Documents::DocumentStore &documents, const SourceCatalog &catalog, + const InstalledSourceGrant &grant, std::uint64_t sequence, + std::span previous_lookups, std::stop_token stop); + +struct StockScan { + std::vector provides, imports; + bool complete{}; +}; + +// Runs the checked P1689 scan for the selected translation unit in the same +// isolated compiler view. The caller owns admission and cancellation. +[[nodiscard]] std::expected +scan_modules_with_gcc(const GccProfile &profile, const SemanticContextLease &lease, + const Documents::DocumentStore &documents, const SourceCatalog &catalog, + const InstalledSourceGrant &grant, + std::span previous_lookups, + std::stop_token stop); + +} // namespace vls::semantic diff --git a/src/Build/CommandImport.cpp b/src/Build/CommandImport.cpp new file mode 100644 index 0000000..483077b --- /dev/null +++ b/src/Build/CommandImport.cpp @@ -0,0 +1,692 @@ +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Build { +namespace { +namespace fs = std::filesystem; +using Protocol::Json; +using Strings = std::vector; +template using Result = std::expected; + +constexpr std::size_t mib = 1024 * 1024; +constexpr std::size_t max_rows = 32 * 1024, max_row_bytes = 2 * mib, max_row_marks = 16 * 1024; +constexpr std::size_t max_row_depth = 31; // Plus the top-level array. +constexpr std::size_t max_args = 4096, max_arg_bytes = 64 * 1024, max_argv_bytes = mib; +constexpr std::size_t max_path_bytes = 4095; + +bool consume(std::string_view &text, char byte) { + const auto start = text.find_first_not_of(" \t\r\n"); + text.remove_prefix(std::min(start, text.size())); + if (!text.starts_with(byte)) + return false; + text.remove_prefix(1); + return true; +} + +// Locate one bounded object. StrictJson owns all JSON value, key and escape validation. +Result take_row(std::string_view &text) { + if (!text.starts_with('{')) + return std::unexpected("expected a compilation database row object"); + bool quoted = false, escaped = false; + std::size_t depth = 0, marks = 0; + for (std::size_t i = 0; i < std::min(text.size(), max_row_bytes); ++i) { + const char c = text[i]; + if (quoted) { + if (escaped) + escaped = false; + else if (c == '\\') + escaped = true; + else if (c == '"') + quoted = false; + continue; + } + if (c == '"') + quoted = true; + else if (c == '[' || c == '{') { + if (++depth > max_row_depth) + return std::unexpected("row nesting limit exceeded"); + } else if (c == ']' || c == '}') { + if (--depth == 0) { + const auto row = text.substr(0, i + 1); + text.remove_prefix(i + 1); + return row; + } + } else if (c != ',') + continue; + if (++marks > max_row_marks) + return std::unexpected("row structural token limit exceeded"); + } + return std::unexpected("unterminated or oversized compilation database row"); +} + +bool path_text(std::string_view text) { + return !text.empty() && text.size() <= max_path_bytes && !text.contains('\0'); +} + +bool has_parent_step(const fs::path &path) { + return std::ranges::find(path, fs::path{".."}) != path.end(); +} + +bool in_workspace(const fs::path &path, const fs::path &root) { + return std::ranges::starts_with(path, root); +} + +// Preserve parent steps for the scoped filesystem walk. Their meaning depends on +// every preceding component, including a directory symlink. +Result resolve_path(const fs::path &base, std::string_view text, bool directory) { + if (!path_text(text)) + return std::unexpected("invalid or oversized path"); + const fs::path spelling{text}; + if (!directory && (!spelling.has_filename() || spelling.filename() == "." || + spelling.filename() == "..")) + return std::unexpected("expected a file name"); + auto joined = base / spelling; + if (!has_parent_step(joined)) + joined = joined.lexically_normal(); + if (directory && !joined.has_filename() && joined != joined.root_path()) + joined = joined.parent_path(); + if (!joined.is_absolute() || joined.native().size() > max_path_bytes) + return std::unexpected("invalid resolved path"); + return joined; +} + +struct Arguments { + Strings values; + std::size_t bytes{}; + + bool append(std::string_view value) { + if (values.size() == max_args || value.size() > max_arg_bytes || + value.size() > max_argv_bytes - bytes || value.contains('\0')) + return false; + values.emplace_back(value); + bytes += value.size(); + return true; + } +}; + +enum class Syntax { command, gcc_response, clang_response }; + +bool separator(char c, Syntax syntax) { + return c == ' ' || c == '\t' || (syntax != Syntax::command && (c == '\r' || c == '\n')) || + (syntax == Syntax::gcc_response && (c == '\v' || c == '\f')); +} + +bool command_expansion(char c, char quote, bool started) { + if (quote == '\'') + return false; + if (c == '$' || c == '`') + return true; + return !quote && (std::string_view("|&;<>()*?[]{}").contains(c) || + (!started && (c == '~' || c == '#'))); +} + +Result tokenize(std::string_view text, Syntax syntax) { + if (text.contains('\0') || !Unicode::validate_utf8(text) || text.starts_with("\xef\xbb\xbf")) + return std::unexpected("unsupported command text encoding"); + Arguments result; + std::string token; + char quote = 0; + bool started = false; + for (std::size_t i = 0; i < text.size(); ++i) { + char c = text[i]; + if (!quote && separator(c, syntax)) { + if (started && !result.append(token)) + return std::unexpected("command argument limit exceeded"); + started = false; + token.clear(); + continue; + } + if (syntax == Syntax::command && command_expansion(c, quote, started)) + return std::unexpected("unsupported shell expansion or control operator"); + if ((c == '\'' || c == '"') && (!quote || quote == c)) { + quote = quote ? 0 : c; + started = true; + continue; + } + // Clang GNU response files escape the next byte in either quote style. GCC's + // libiberty keeps single quotes literal and limits escapes inside double quotes. + if (c == '\\' && (syntax == Syntax::clang_response || quote != '\'')) { + if (i + 1 == text.size()) + return std::unexpected("incomplete backslash escape"); + const char next = text[i + 1]; + const bool escapes = syntax == Syntax::clang_response || quote != '"' || next == '$' || + next == '`' || next == '"' || next == '\\' || next == '\n'; + if (escapes) { + c = text[++i]; + if (syntax == Syntax::gcc_response && c == '\n') { + started = true; + continue; + } + } + } + if (static_cast(c) < 32 || c == 127) + return std::unexpected("unsupported control character in argument"); + if (token.size() == max_arg_bytes) + return std::unexpected("command argument byte limit exceeded"); + token.push_back(c); + started = true; + } + if (quote) + return std::unexpected("unterminated quoted argument"); + if (started && !result.append(token)) + return std::unexpected("command argument limit exceeded"); + return result; +} + +struct Import { + const DatabaseInput &input; + ImportedCommands output; + // Compare against the first immutable row on every digest tie. + struct Occurrence { + std::string_view first; + std::size_t count{}; + }; + std::map occurrences; + std::map> responses; + std::map, std::size_t> paths; + std::size_t read_attempts{}, remaining_storage{128 * mib}, remaining_expansion{64 * mib}; + bool exhausted{}; + + bool charge(std::size_t &remaining, std::size_t cost) { + if (cost > remaining) { + exhausted = true; + return false; + } + remaining -= cost; + return true; + } + + Result record_id(std::string_view raw) { + const auto digest = Crypto::sha256(raw); + if (!digest) + return std::unexpected("row identity digest unavailable"); + const auto [it, inserted] = + occurrences.try_emplace(Encoding::Hex::encode(*digest), Occurrence{raw}); + if (!inserted && it->second.first != raw) + return std::unexpected("distinct compilation records have identical digests"); + return it->first + "#" + std::to_string(++it->second.count); + } +}; + +std::size_t path_cost(const fs::path &path) { + return path.native().size() + + (sizeof(fs::path) + sizeof(void *)) * static_cast(std::ranges::distance(path)); +} + +Result bind_command_path(Import &state, const fs::path &path, + CommandPathKind kind) { + if (!in_workspace(path, state.input.scope.workspace.root)) + return std::unexpected("out-of-workspace command path"); + const auto key = std::pair{path, kind}; + auto &lookups = state.output.lookups.paths; + auto it = state.paths.find(key); + if (it == state.paths.end()) { + auto lookup = inspect_command_path(state.input.scope, path, kind); + // Includes the bounded link stamps and both retained copies of the logical name. + if (!state.charge(state.remaining_storage, + 1024 + 2 * path_cost(path) + path_cost(lookup.physical_path))) + return std::unexpected("command path storage limit exceeded"); + it = state.paths.emplace(key, lookups.size()).first; + lookups.push_back(std::move(lookup)); + } + const auto &lookup = lookups[it->second]; + if (lookup.physical_path.empty()) + return std::unexpected("unresolved command path (" + lookup.issue + "): " + path.native()); + return &lookup; +} + +// Cache only by logical name. Two hard links or symlinks retain both namespace observations. +Result response_index(Import &state, const fs::path &path, std::size_t byte_limit) { + if (const auto it = state.responses.find(path); it != state.responses.end()) + return it->second; + if (++state.read_attempts > 1024 || state.responses.size() >= 256) { + state.exhausted = true; + return std::unexpected("generation response input limit exceeded"); + } + auto file = read_provider_file(state.input.scope, path, FilePurpose::response, byte_limit); + if (!file) { + if (!state.charge(state.remaining_storage, path_cost(path) + 256)) + return std::unexpected("retained response lookup limit exceeded"); + state.output.lookups.failed_responses.push_back({file.error(), byte_limit}); + if (file.error().code == "too_large") + return std::unexpected("aggregate response byte limit exceeded at " + path.native()); + auto failure = std::unexpected("response file " + file.error().code + " at " + path.native()); + // One observation per logical name for this generation. A byte limit depends on the + // current expansion and must not poison a different row with more remaining budget. + if (!state.charge(state.remaining_storage, path_cost(path) + failure.error().size() + 128)) + return std::unexpected("retained response input limit exceeded"); + state.responses.emplace(path, failure); + return failure; + } + const auto cost = file->bytes->size() + path_cost(path) * 2 + path_cost(file->canonical_path) + 1024; + if (!state.charge(state.remaining_storage, cost)) + return std::unexpected("retained response input limit exceeded"); + const auto index = state.output.dependencies.size(); + state.responses.emplace(path, index); + state.output.dependencies.push_back(std::move(*file)); + return index; +} + +struct Expansion { + Import &state; + const fs::path &cwd; + Syntax syntax; + std::vector active; + Arguments expanded; + std::size_t bytes_left, visits{}; + + Result append(std::span tokens) { + const auto &scope = state.input.scope; + for (const auto &arg : tokens) { + if (!arg.starts_with('@')) { + if (!expanded.append(arg)) + return std::unexpected("expanded argument limit exceeded"); + continue; + } + if (active.size() >= std::min(scope.limits.max_response_file_depth, 32) || + ++visits > 256) + return std::unexpected("response nesting or reference limit exceeded"); + const auto name = std::string_view(arg).substr(1); + auto path = resolve_path(cwd, name, false); + if (!path || has_parent_step(fs::path{name}) || !in_workspace(*path, scope.workspace.root)) + return std::unexpected("response file name outside supported workspace routes"); + auto index = response_index(state, *path, bytes_left); + if (!index) + return std::unexpected(std::move(index.error())); + const auto &file = state.output.dependencies[*index]; + if (std::ranges::any_of(active, [&](auto parent) { + return same_provider_object(state.output.dependencies[parent], file); + })) + return std::unexpected("recursive response file " + path->native()); + if (file.bytes->size() > bytes_left) + return std::unexpected("aggregate response byte limit exceeded"); + bytes_left -= file.bytes->size(); + if (!state.charge(state.remaining_expansion, file.bytes->size() + 128)) + return std::unexpected("generation response expansion limit exceeded"); + auto nested = tokenize(*file.bytes, syntax); + if (!nested) + return std::unexpected(std::move(nested.error())); + active.push_back(*index); + auto accepted = append(nested->values); + active.pop_back(); + if (!accepted) + return accepted; + } + return {}; + } +}; + +Result check_prefix(const DatabaseInput &input, std::span raw) { + if (!input.driver) + return std::unexpected("no checked compiler for this workspace"); + const auto &driver = *input.driver; + const auto &tool = driver.tool; + if (tool.workspace_root != input.scope.workspace.root || + tool.operation != Workspace::AuthorityLevel::compiler_use || !tool.trust_generation) + return std::unexpected("compiler check has a different workspace, purpose or generation"); + // Trust checks bounds, controls, wrappers, compiler spelling and dialect before examining + // operands. Only these three post-prefix classifications can require provider normalization. + // The final classifier must accept the entire expanded command. + using enum Workspace::FlagClassification; + const auto checked = Workspace::classify_and_unwrap_command(raw, driver.wrappers, tool.identity, + driver.driver); + if (!checked.allowed && checked.classification != unresolved_response_file && + checked.classification != unsupported_operand && checked.classification != unsupported_option) + return std::unexpected(std::string(checked.reason)); + auto compiler = std::ranges::find(raw, tool.identity.selected_path.native()); + if (compiler == raw.end()) + return std::unexpected("argv lacks the exact selected compiler spelling"); + return static_cast(compiler - raw.begin()) + 1; +} + +Result semantic_path(Import &state, const fs::path &cwd, + std::string_view value, bool directory) { + auto path = resolve_path(cwd, value, directory); + if (!path || has_parent_step(*path)) + return std::unexpected("ambiguous or out-of-workspace compiler path"); + return bind_command_path(state, *path, directory ? CommandPathKind::directory : CommandPathKind::file); +} + +// Keep separate and joined operands distinct. In particular a separate -I consumes its +// following token, even when that token spells -o. Unknown flags go to Trust unchanged. +Result normalize(Import &state, const DriverInput &driver, BuildContext &context, + std::span expanded, std::size_t prefix_size, + const std::string *row_output) { + const auto &cwd = *context.working_directory; + Arguments semantic; + bool compile = false, matches_tu = false; + std::optional output; + fs::path compiler_source; + std::optional language, tu_language; + for (std::size_t i = 0; i < expanded.size(); ++i) { + const std::string_view arg = expanded[i]; + std::string rewritten; + if (i < prefix_size) { + if (!semantic.append(arg)) + return std::unexpected("normalized argument limit exceeded"); + continue; + } + if (arg == "-o") { + if (output || ++i == expanded.size() || expanded[i].starts_with('-')) + return std::unexpected("ambiguous compile output operand"); + auto resolved = semantic_path(state, cwd, expanded[i], false); + if (!resolved) + return std::unexpected(std::move(resolved.error())); + output = (*resolved)->physical_path; + continue; + } + constexpr std::string_view options[]{"-I", "-isystem", "-iquote", "-D", "-U", "-x"}; + auto op = std::ranges::find_if(options, [&](auto option) { return arg.starts_with(option); }); + if (op != std::end(options)) { + auto value = arg.substr(op->size()); + const bool separate = value.empty(); + if (separate) { + if (++i == expanded.size()) + return std::unexpected("missing compiler option operand"); + value = expanded[i]; + if (!semantic.append(*op)) + return std::unexpected("normalized argument limit exceeded"); + } else { + rewritten = *op; + } + if (*op == "-I" || *op == "-isystem" || *op == "-iquote") { + if (value.empty() || value == "-" || value.starts_with('=') || + value.starts_with("$SYSROOT") || (!separate && value.starts_with('-'))) + return std::unexpected("unsupported search-path operand"); + auto path = semantic_path(state, cwd, value, true); + if (!path) + return std::unexpected(std::move(path.error())); + rewritten += (*path)->logical_path.native(); + } else { + rewritten += value; + if (*op == "-x") + language = value; + } + } else if (!arg.starts_with('-')) { + auto source = semantic_path(state, cwd, arg, false); + if (!source) + return std::unexpected(std::move(source.error())); + compiler_source = (*source)->logical_path; + rewritten = compiler_source.native(); + matches_tu = (*source)->physical_path == context.key.owning_tu; + tu_language = language; + } else { + compile |= arg == "-c"; + rewritten = arg; + } + if (!semantic.append(rewritten)) + return std::unexpected("normalized argument limit exceeded"); + } + if (output) { + if (!compile) + return std::unexpected("an explicit output requires a compile-only command"); + if (row_output) { + auto declared = semantic_path(state, cwd, *row_output, false); + if (!declared || *output != (*declared)->physical_path) + return std::unexpected("compiler output differs from the row output"); + } + } + auto report = Workspace::classify_and_unwrap_command(semantic.values, driver.wrappers, + driver.tool.identity, driver.driver); + if (!report.allowed) + return std::unexpected(std::string(report.reason)); + if (!matches_tu) + return std::unexpected("the classified translation unit differs from the row file"); + if (!tu_language) { + // Both admitted driver dialects select C++ from the actual operand spelling. + // A symlink to a generated file can have a different suffix from its target. + constexpr std::string_view cxx_suffixes[]{".C", ".cc", ".cp", ".cpp", ".cxx", ".c++"}; + if (std::ranges::contains(cxx_suffixes, compiler_source.extension().native())) + tu_language = "c++"; + } + context.semantic_arguments = std::move(report.unwrapped_argv); + context.source_language = std::move(tu_language); + context.sources.front().compiler_path = std::move(compiler_source); + return {}; +} + +Result analyze(Import &state, BuildContext &context, const fs::path &directory, + const fs::path &filename, const std::string *output) { + const auto &input = state.input; + const auto &root = input.scope.workspace.root; + if (has_parent_step(directory) || has_parent_step(filename) || + !in_workspace(*context.working_directory, root) || !in_workspace(context.key.owning_tu, root)) + return std::unexpected("row working directory or file has an ambiguous or external route"); + + const auto &original = *context.original; + Arguments command; + if (!original.arguments) { + auto tokens = tokenize(*original.command, Syntax::command); + if (!tokens) + return std::unexpected(std::move(tokens.error())); + command = std::move(*tokens); + } + const auto &raw = original.arguments ? *original.arguments : command.values; + auto prefix = check_prefix(input, raw); + if (!prefix) + return std::unexpected(std::move(prefix.error())); + const auto &driver = *input.driver; + if (std::ranges::any_of(raw, [](std::string_view arg) { + return arg.starts_with("--driver-mode") || arg.starts_with("--rsp-quoting"); + })) + return std::unexpected("driver mode or response syntax override"); + Expansion expansion{.state = state, + .cwd = *context.working_directory, + .syntax = driver.driver == Workspace::CompilerDriver::gcc ? Syntax::gcc_response + : Syntax::clang_response, + .bytes_left = std::min(input.scope.limits.max_response_file_bytes, 16 * mib)}; + auto expanded = expansion.append(raw); + if (!expanded) + return expanded; + return normalize(state, driver, context, expansion.expanded.values, *prefix, output); +} + +Result import_row(Import &state, std::string_view raw) { + auto json = Protocol::parse_json(raw, max_row_depth); + if (!json) + return std::unexpected(std::move(json.error())); + const auto &object = std::get(json->value); // take_row requires an object. + const auto field = [&](std::string_view key) { return Protocol::find_member(object, key); }; + const auto *directory = Protocol::as_string(field("directory")); + const auto *file = Protocol::as_string(field("file")); + const auto *args = Protocol::as_array(field("arguments")); + const auto *command = Protocol::as_string(field("command")); + const auto *output = Protocol::as_string(field("output")); + if (!directory || !file || (field("command") && !command) || (field("arguments") && !args) || + (field("output") && (!output || !path_text(*output))) || (!args && !command)) + return std::unexpected("invalid compilation database field type or missing required field"); + if (command && (command->size() > max_argv_bytes || command->contains('\0'))) + return std::unexpected("invalid command string"); + const auto &input = state.input; + auto cwd = resolve_path(input.database.logical_path.parent_path(), *directory, true); + if (!cwd) + return std::unexpected(std::move(cwd.error())); + auto tu = resolve_path(*cwd, *file, false); + if (!tu) + return std::unexpected(std::move(tu.error())); + auto id = state.record_id(raw); + if (!id) + return std::unexpected(std::move(id.error())); + + OriginalCommand original{.metadata_file = input.database.logical_path, + .record_id = *id, + .original_record = std::string(raw)}; + std::size_t cost = 1536 + raw.size() + path_cost(original.metadata_file) + path_cost(*cwd) + + 3 * path_cost(*tu) + (input.profile ? input.profile->size() : 0); + if (args) { + if (args->empty() || args->size() > max_args) + return std::unexpected("expected a nonempty argument array within the count limit"); + Arguments typed; + for (const auto &arg : *args) { + const auto *value = Protocol::as_string(&arg); + if (!value || !typed.append(*value)) + return std::unexpected("invalid or oversized arguments array"); + } + cost += typed.values.capacity() * sizeof(std::string) + typed.bytes; + original.arguments = std::move(typed.values); + } + if (command) { + original.command = *command; + cost += command->size(); + } + if (!state.charge(state.remaining_storage, cost)) + return std::unexpected("generation storage limit exceeded"); + BuildContext context; + context.key = {.profile = input.profile, .alternative = std::move(*id)}; + context.original = std::move(original); + auto location = bind_command_path(state, *cwd, CommandPathKind::directory); + if (location) + context.working_directory = has_parent_step(*cwd) ? (*location)->physical_path : *cwd; + auto owner = bind_command_path(state, *tu, CommandPathKind::file); + if (owner) { + context.key.owning_tu = (*owner)->physical_path; + context.sources.push_back({.source_path = context.key.owning_tu}); + } + Result result; + if (!owner) + result = std::unexpected(std::move(owner.error())); + else if (!location) + result = std::unexpected(std::move(location.error())); + else + result = analyze(state, context, *directory, *file, output); + if (state.exhausted) + return std::unexpected("generation resource limit exceeded"); + if (!result) { + if (!state.charge(state.remaining_storage, result.error().size())) + return std::unexpected("generation storage limit exceeded"); + context.limitations.push_back(std::move(result.error())); + } else { + std::size_t semantic_bytes = context.semantic_arguments->capacity() * sizeof(std::string); + for (const auto &arg : *context.semantic_arguments) + semantic_bytes += arg.size(); + if (!state.charge(state.remaining_storage, semantic_bytes)) + return std::unexpected("generation storage limit exceeded"); + } + state.output.contexts.push_back(std::move(context)); + return {}; +} + +// Include the observed driver, row outcomes and every logical response name and content. +// Length framing makes field boundaries independent of the bytes in a POSIX path or flag. +Result revision(const Import &state) { + auto hash = Crypto::Hasher::create(Crypto::HashAlgorithm::Sha256); + if (!hash) + return std::unexpected("compilation database revision digest unavailable"); + bool complete = true; + const auto add = [&](std::string_view value) { + const auto length = std::to_string(value.size()) + "/"; + complete = complete && hash->update(length).has_value() && hash->update(value).has_value(); + }; + const auto &input = state.input; + add(input.database.logical_path.native()); + add(input.database.canonical_path.native()); + add(input.database.content_id); + add(input.profile.value_or("")); + if (input.driver) { + const auto &driver = *input.driver; + add("driver"); + add(std::to_string(static_cast(driver.driver))); + add(driver.tool.workspace_root.native()); + add(std::to_string(static_cast(driver.tool.operation))); + add(std::to_string(driver.tool.trust_generation)); + const auto &identity = driver.tool.identity; + add(identity.selected_path.native()); + add(identity.canonical_path.native()); + add(std::to_string(identity.device)); + add(std::to_string(identity.inode)); + add(std::to_string(identity.file_size)); + add(std::to_string(identity.mode)); + add(std::to_string(identity.owner)); + add(std::to_string(identity.group)); + add(identity.content_hash_hex); + const auto &origin = driver.tool.selection_origin; + add(std::to_string(static_cast(origin.layer))); + add(origin.base.native()); + add(origin.selected_file ? origin.selected_file->native() : ""); + add(std::to_string(origin.revision)); + add(std::to_string(driver.wrappers.size())); + for (const auto &wrapper : driver.wrappers) + add(wrapper); + } else + add("no driver"); + add(std::to_string(state.output.contexts.size())); + for (const auto &row : state.output.contexts) + add(row.limitations.empty() ? std::string_view{} : row.limitations.front()); + for (const auto &file : state.output.dependencies) { + add(file.logical_path.native()); + add(file.canonical_path.native()); + add(file.content_id); + } + for (const auto &lookup : state.output.lookups.paths) { + add(lookup.logical_path.native()); + add(lookup.physical_path.native()); + add(lookup.issue); + } + for (const auto &failed : state.output.lookups.failed_responses) { + add(failed.issue.path.native()); + add(failed.issue.code); + add(std::to_string(failed.byte_limit)); + } + auto digest = hash->finalize(); + if (!complete || !digest) + return std::unexpected("compilation database revision digest unavailable"); + return Encoding::Hex::encode(*digest); +} +} // namespace + +std::expected import_commands(const DatabaseInput &input) { + const auto &db = input.database; + auto fail = [&](std::string message) { + return std::unexpected(ProviderIssue{"invalid_database", std::move(message), db.logical_path}); + }; + if (!db.bytes || !db.stamp || db.content_id.empty() || !db.logical_path.is_absolute() || + (db.purpose != FilePurpose::database && db.purpose != FilePurpose::native_database)) + return fail("expected an acquired compilation database"); + if (!provider_file_current(input.scope, db)) + return std::unexpected(ProviderIssue{"changed", "Compilation database binding changed", db.logical_path}); + if (input.profile && !path_text(*input.profile)) + return fail("invalid compilation profile"); + if (db.bytes->size() > input.scope.limits.max_compdb_bytes) + return fail("compilation database byte limit exceeded"); + Import state{.input = input}; + std::string_view text = *db.bytes; + if (!consume(text, '[')) + return fail("expected a compilation database array"); + if (!consume(text, ']')) { + for (;;) { + if (state.output.contexts.size() == max_rows) + return fail("compilation database row limit exceeded"); + auto row = take_row(text); + if (!row) + return fail(std::move(row.error())); + auto accepted = import_row(state, *row); + if (!accepted) + return fail("row " + std::to_string(state.output.contexts.size() + 1) + " — " + + accepted.error()); + if (consume(text, ']')) + break; + if (!consume(text, ',')) + return fail("expected a comma or end of compilation database"); + const auto next = text.find_first_not_of(" \r\n\t"); + text.remove_prefix(std::min(next, text.size())); + } + } + if (text.find_first_not_of(" \r\n\t") != text.npos) + return fail("trailing data after compilation database"); + auto identity = revision(state); + if (!identity) + return fail(std::move(identity.error())); + state.output.revision = std::move(*identity); + return std::move(state.output); +} +} // namespace Void::LanguageServer::Build diff --git a/src/Build/CompdbProvider.cpp b/src/Build/CompdbProvider.cpp new file mode 100644 index 0000000..50a1ef9 --- /dev/null +++ b/src/Build/CompdbProvider.cpp @@ -0,0 +1,51 @@ +#include + +#include + +namespace Void::LanguageServer::Build { + +ProviderObservation observe_compdb(const ProviderScope &scope, const std::filesystem::path &path, + const std::optional &driver) { + ProviderObservation result{.provider = "compdb"}; + auto file = + read_provider_file(scope, path, FilePurpose::database, scope.limits.max_compdb_bytes); + if (!file) { + if (file.error().code == "missing") + result.health = ProviderHealth::missing; + else if (file.error().code == "changed") + result.health = ProviderHealth::changed; + result.issues.push_back(std::move(file.error())); + return result; + } + result.inputs.push_back(std::move(*file)); + auto commands = import_commands({scope, result.inputs.front(), std::nullopt, driver}); + if (commands) { + const auto &logical = result.inputs.front().logical_path.native(); + auto revision = std::to_string(logical.size()) + "/" + logical + "/" + + result.inputs.front().content_id + "/" + commands->revision; + auto generation = BuildGeneration::create({scope.workspace, "compdb", std::move(revision)}, + commands->contexts); + result.inputs.insert(result.inputs.end(), + std::make_move_iterator(commands->dependencies.begin()), + std::make_move_iterator(commands->dependencies.end())); + result.lookups = std::move(commands->lookups); + if (generation) { + result.generation = std::move(*generation); + result.health = ProviderHealth::ready; + } else { + result.health = ProviderHealth::invalid; + result.issues.push_back( + {"invalid_context", "Invalid compilation database context", path}); + } + } else { + result.health = ProviderHealth::invalid; + result.issues.push_back(std::move(commands.error())); + } + if (auto changed = changed_provider_input(scope, result)) { + result.health = ProviderHealth::changed; + result.generation.reset(); + result.issues = {{"changed", "Compilation inputs changed during observation", *changed}}; + } + return result; +} +} // namespace Void::LanguageServer::Build diff --git a/src/Build/Model.cpp b/src/Build/Model.cpp new file mode 100644 index 0000000..c6f9b89 --- /dev/null +++ b/src/Build/Model.cpp @@ -0,0 +1,600 @@ +#include + +#include +#include +#include +#include + +namespace Void::LanguageServer::Build { +namespace { +namespace fs = std::filesystem; + +bool identifier(const std::string &value) { return !value.empty() && !value.contains('\0'); } + +bool valid_optional(const std::optional &value) { + return !value || identifier(*value); +} + +bool absolute_path(const fs::path &path) { + return path.is_absolute() && !path.native().contains(fs::path::value_type{}) && + path == path.lexically_normal() && (path == path.root_path() || path.has_filename()); +} + +bool file_path(const fs::path &path) { return absolute_path(path) && path.has_filename(); } + +bool under_root(const fs::path &path, const fs::path &root) { + const auto [r, p] = std::mismatch(root.begin(), root.end(), path.begin(), path.end()); + return r == root.end() && p != path.end(); +} + +bool valid_key(const ContextKey &key, bool allow_unresolved = false) { + return identifier(key.alternative) && + (file_path(key.owning_tu) || (allow_unresolved && key.owning_tu.empty())) && valid_optional(key.profile) && + valid_optional(key.target) && + (key.role == ContextRole::target || key.role == ContextRole::host_description || + key.role == ContextRole::unknown); +} + +bool valid_arguments(const std::optional> &arguments) { + return !arguments || + std::ranges::none_of(*arguments, [](const auto &arg) { return arg.contains('\0'); }); +} + +bool valid_availability(Availability availability) { + return availability == Availability::unknown || availability == Availability::missing || + availability == Availability::stale || availability == Availability::ready; +} + +bool valid_mapping(const SourceMapping &source, const fs::path &root) { + const bool known_origin = + source.origin == SourceOrigin::unknown || source.origin == SourceOrigin::workspace || + source.origin == SourceOrigin::snapshot || source.origin == SourceOrigin::generated || + source.origin == SourceOrigin::external; + const bool known_editability = source.editability == Editability::unknown || + source.editability == Editability::editable || + source.editability == Editability::read_only; + return known_origin && known_editability && file_path(source.source_path) && + (!source.compiler_path || file_path(*source.compiler_path)) && + valid_optional(source.provenance) && + (source.origin != SourceOrigin::workspace || under_root(source.source_path, root)); +} + +std::expected prepare_context(BuildContext &context, const fs::path &root) { + const bool unresolved = context.key.owning_tu.empty(); + if (!valid_key(context.key, true) || !valid_optional(context.source_language) || + !valid_optional(context.toolchain) || !valid_optional(context.standard_library) || + !valid_optional(context.environment) || !valid_arguments(context.semantic_arguments) || + (context.working_directory && !absolute_path(*context.working_directory))) { + return std::unexpected(ModelError::invalid_context); + } + if (context.original) { + const auto &raw = *context.original; + if (!file_path(raw.metadata_file) || !identifier(raw.record_id) || + !valid_arguments(raw.arguments)) { + return std::unexpected(ModelError::invalid_context); + } + } + if (context.prerequisites && !std::ranges::all_of(*context.prerequisites, [](const auto &p) { + return identifier(p.name) && valid_optional(p.input_identity) && + valid_availability(p.state); + })) { + return std::unexpected(ModelError::invalid_context); + } + if (context.artifacts && !std::ranges::all_of(*context.artifacts, [](const auto &a) { + return file_path(a.path) && valid_optional(a.content_identity) && + valid_availability(a.state); + })) { + return std::unexpected(ModelError::invalid_context); + } + + std::ranges::sort(context.sources, {}, &SourceMapping::source_path); + const fs::path *previous = nullptr; + for (const auto &source : context.sources) { + if (!valid_mapping(source, root) || (previous && *previous == source.source_path)) { + return std::unexpected(ModelError::invalid_mapping); + } + previous = &source.source_path; + } + if (unresolved) { + if (!context.original || !context.original->original_record || context.limitations.empty() || + !context.sources.empty() || context.semantic_arguments) + return std::unexpected(ModelError::invalid_mapping); + } else if (!context.mapping_for(context.key.owning_tu)) { + return std::unexpected(ModelError::invalid_mapping); + } + return {}; +} + +bool editor_matches(const EditorSelection &editor, const ContextKey &key) { + return (!editor.profile || editor.profile == key.profile) && + (!editor.target || editor.target == key.target) && + (!editor.alternative || *editor.alternative == key.alternative) && + (!editor.role || *editor.role == key.role); +} + +bool same_source(const Snapshot &a, const Snapshot &b) { + return a == b || (a && b && a->same_input_as(*b)); +} + +bool same_dependencies(const std::optional> &a, + const std::optional> &b) { + if (!a || !b) { + return a.has_value() == b.has_value(); + } + return std::ranges::equal(*a, *b, [](const auto &left, const auto &right) { + return left.kind == right.kind && left.name == right.name && + left.lookup_path == right.lookup_path && same_source(left.source, right.source); + }); +} + +bool valid_snapshot(const Snapshot &snapshot) { + return snapshot && snapshot->revision_id != 0 && snapshot->identity.is_file_uri && + identifier(snapshot->identity.canonical_uri) && + file_path(snapshot->identity.canonical_path) && + ((snapshot->origin == Documents::DocumentOrigin::overlay && snapshot->version) || + (snapshot->origin == Documents::DocumentOrigin::disk && !snapshot->version)); +} + +bool consistent_sources(const AnalysisInputs &inputs) { + std::map seen; + auto record = [&](const Snapshot &source) { + if (!valid_snapshot(source)) { + return false; + } + const auto [it, inserted] = seen.emplace(source->identity.canonical_path, source.get()); + return inserted || it->second == source.get() || it->second->same_input_as(*source); + }; + if ((inputs.document && !record(inputs.document)) || + (inputs.translation_unit && !record(inputs.translation_unit))) { + return false; + } + return !inputs.dependencies || std::ranges::all_of(*inputs.dependencies, [&](const auto &dep) { + return identifier(dep.name) && file_path(dep.lookup_path) && record(dep.source); + }); +} + +std::expected validate_coverage(const RenameCoverage &coverage, + const ContextSelection &selection) { + const auto &workspace = selection.scope->workspace; + std::set roots; + for (const auto &root : coverage.workspace_roots) { + if (!absolute_path(root) || !roots.insert(root).second) { + return std::unexpected(ModelError::invalid_input); + } + } + if (!roots.contains(workspace.root)) { + return std::unexpected(ModelError::wrong_scope); + } + if (!valid_optional(coverage.editable_spelling_proof)) { + return std::unexpected(ModelError::invalid_input); + } + if (!coverage.contexts) { + return {}; + } + std::map, const BuildGeneration *> generations; + const auto &selected = selection.generation->identity(); + generations.emplace(std::pair{workspace.root, selected.provider}, selection.generation.get()); + std::set seen; + for (const auto &proof : *coverage.contexts) { + if (!proof.generation || !valid_optional(proof.verification)) { + return std::unexpected(ModelError::invalid_input); + } + const auto &id = proof.generation->identity(); + if (id.workspace.session != workspace.session || !roots.contains(id.workspace.root)) { + return std::unexpected(ModelError::wrong_scope); + } + const auto [it, inserted] = + generations.emplace(std::pair{id.workspace.root, id.provider}, proof.generation.get()); + const auto *context = proof.generation->find(proof.key); + if ((!inserted && it->second != proof.generation.get()) || !context || + !seen.insert(context).second) { + return std::unexpected(ModelError::invalid_input); + } + } + return {}; +} + +bool known_mapping(const SourceMapping *mapping) { + return mapping && mapping->compiler_path && mapping->origin != SourceOrigin::unknown && + mapping->provenance; +} + +struct ContextReadiness { + bool diagnostic_command{}; + std::vector missing; +}; + +ContextReadiness assess_context(const BuildGeneration &generation, const BuildContext &context, + const fs::path &file) { + ContextReadiness facts; + auto need = [&](bool available, InputIssue issue) { + if (!available) { + facts.missing.push_back(issue); + } + }; + need(context.source_language.has_value(), InputIssue::language); + need(context.semantic_arguments && !context.semantic_arguments->empty() && + !context.semantic_arguments->front().empty(), + InputIssue::command); + need(context.working_directory.has_value(), InputIssue::working_directory); + facts.diagnostic_command = facts.missing.empty(); + + const auto &raw = context.original; + need(raw && ((raw->arguments && !raw->arguments->empty() && !raw->arguments->front().empty()) || + (raw->command && identifier(*raw->command)) || + (raw->original_record && !raw->original_record->empty())), + InputIssue::command_provenance); + need(known_mapping(context.mapping_for(context.key.owning_tu)) && + known_mapping(context.mapping_for(file)), + InputIssue::source_mapping); + need(context.toolchain.has_value(), InputIssue::toolchain); + need(context.standard_library.has_value(), InputIssue::standard_library); + need(context.environment.has_value(), InputIssue::environment); + need(context.prerequisites && std::ranges::all_of(*context.prerequisites, + [](const auto &p) { + return p.state == Availability::ready && + p.input_identity; + }), + InputIssue::prerequisites); + need(context.artifacts && std::ranges::all_of(*context.artifacts, + [&](const auto &artifact) { + return artifact.state == + Availability::ready && + artifact.content_identity && + generation.retains_artifacts(); + }), + InputIssue::artifacts); + need(context.limitations.empty(), InputIssue::provider_limitation); + return facts; +} + +bool covered(const ContextSelection &selection, const RenameCoverage &coverage) { + if (!selection.selected || !coverage.contexts) { + return false; + } + std::set verified; + std::set generations{selection.generation.get()}; + for (const auto &proof : *coverage.contexts) { + if (!proof.verification) { + return false; + } + const auto *context = proof.generation->find(proof.key); + const auto &file = context->mapping_for(selection.scope->file) ? selection.scope->file + : proof.key.owning_tu; + if (!assess_context(*proof.generation, *context, file).missing.empty()) { + return false; + } + generations.insert(proof.generation.get()); + verified.insert(context); + } + for (const auto *generation : generations) { + if (!std::ranges::all_of(generation->candidates(selection.scope->file), + [&](auto candidate) { return verified.contains(candidate); })) { + return false; + } + } + return true; +} + +std::array assess(const ContextSelection &selection, const AnalysisInputs &inputs) { + std::vector issues; + auto need = [&](bool available, InputIssue issue) { + if (!available) { + issues.push_back(issue); + } + }; + const auto *context = selection.selected; + need(context != nullptr, InputIssue::context); + need(inputs.document != nullptr, InputIssue::document); + need(inputs.translation_unit != nullptr, InputIssue::translation_unit); + need(inputs.backend.has_value(), InputIssue::backend); + need(inputs.configuration_generation.has_value(), InputIssue::configuration); + need(inputs.trust_generation.has_value(), InputIssue::trust); + bool diagnostic_inputs = issues.empty(); + if (context) { + auto facts = assess_context(*selection.generation, *context, selection.scope->file); + diagnostic_inputs = diagnostic_inputs && facts.diagnostic_command; + issues.append_range(facts.missing); + } + need(inputs.dependencies.has_value(), InputIssue::dependencies); + need(inputs.lookup_epoch.has_value(), InputIssue::lookup_coverage); + + const auto observed = issues.empty() ? ReadinessLevel::ready : ReadinessLevel::degraded; + const Readiness status{observed, issues}; + const Readiness diagnostics{diagnostic_inputs ? observed : ReadinessLevel::unavailable, issues}; + const Readiness semantic{issues.empty() ? ReadinessLevel::ready : ReadinessLevel::unavailable, + issues}; + need(inputs.rename && covered(selection, *inputs.rename), InputIssue::affected_contexts); + const auto *document_mapping = context ? context->mapping_for(selection.scope->file) : nullptr; + need(document_mapping && document_mapping->editability == Editability::editable && + inputs.rename && inputs.rename->editable_spelling_proof, + InputIssue::edit_provenance); + return {status, diagnostics, semantic, + Readiness{issues.empty() ? ReadinessLevel::ready : ReadinessLevel::unavailable, + std::move(issues)}}; +} + +bool regresses(std::optional value, std::optional floor) { + return value && floor && *value < *floor; +} +} // namespace + +const SourceMapping *BuildContext::mapping_for(const fs::path &source) const { + const auto it = std::ranges::find(sources, source, &SourceMapping::source_path); + return it != sources.end() ? &*it : nullptr; +} + +BuildGeneration::BuildGeneration(GenerationIdentity identity, std::vector records, + std::shared_ptr lease) + : identity_(std::move(identity)), records_(std::move(records)), lease_(std::move(lease)) { + for (const auto &record : records_) { + for (const auto &source : record.sources) { + by_source_[source.source_path].push_back(&record); + } + } +} + +std::expected +BuildGeneration::create(const GenerationIdentity &identity, + const std::vector &supplied, + std::shared_ptr lease) { + if (!absolute_path(identity.workspace.root) || !identifier(identity.workspace.session) || + !identifier(identity.provider) || !identifier(identity.revision)) { + return std::unexpected(ModelError::invalid_identity); + } + auto records = supplied; + std::ranges::sort(records, {}, &BuildContext::key); + const ContextKey *previous = nullptr; + for (auto &context : records) { + if (previous && *previous == context.key) { + return std::unexpected(ModelError::duplicate_context); + } + if (auto valid = prepare_context(context, identity.workspace.root); !valid) { + return std::unexpected(valid.error()); + } + previous = &context.key; + } + return Generation{new BuildGeneration(identity, std::move(records), std::move(lease))}; +} + +std::span BuildGeneration::candidates(const fs::path &source) const { + const auto it = by_source_.find(source); + if (it == by_source_.end()) { + return {}; + } + return it->second; +} + +const BuildContext *BuildGeneration::find(const ContextKey &key) const { + if (key.owning_tu.empty()) + return nullptr; + const auto it = std::ranges::lower_bound(records_, key, {}, &BuildContext::key); + return it != records_.end() && it->key == key ? &*it : nullptr; +} + +ContextSelection::ContextSelection(std::shared_ptr scope, + Generation generation, std::uint64_t revision, + std::optional file_override, + std::optional editor, SelectionReason reason, + const BuildContext *selected) + : scope(std::move(scope)), generation(std::move(generation)), revision(revision), + file_override(std::move(file_override)), editor(std::move(editor)), reason(reason), + selected(selected) {} + +SelectionState::SelectionState(const WorkspaceIdentity &workspace, const fs::path &file) + : scope_(std::make_shared(workspace, file)) {} + +std::expected +SelectionState::update(Generation generation, const std::optional &file_override, + const std::optional &editor) { + if (!generation || !file_path(scope_->file)) { + return std::unexpected(ModelError::invalid_identity); + } + if (generation->identity().workspace != scope_->workspace || + (file_override && (file_override->workspace_root != scope_->workspace.root || + file_override->file != scope_->file)) || + (editor && editor->workspace_root != scope_->workspace.root)) { + return std::unexpected(ModelError::wrong_scope); + } + if ((file_override && + (!identifier(file_override->provider) || !valid_key(file_override->key))) || + (editor && (!identifier(editor->provider) || !valid_optional(editor->profile) || + !valid_optional(editor->target) || !valid_optional(editor->alternative) || + !(editor->profile || editor->target || editor->alternative || editor->role)))) { + return std::unexpected(ModelError::invalid_identity); + } + if (current_ && current_->generation == generation && + current_->file_override == file_override && current_->editor == editor) { + return current_; + } + if (current_ && current_->revision == std::numeric_limits::max()) { + return std::unexpected(ModelError::sequence_exhausted); + } + const auto candidates = generation->candidates(scope_->file); + const BuildContext *selected = nullptr; + auto reason = SelectionReason::no_owner; + if (file_override) { + if (file_override->provider == generation->identity().provider) { + selected = generation->find(file_override->key); + } + if (selected && selected->mapping_for(scope_->file)) { + reason = SelectionReason::file_override; + } else { + reason = SelectionReason::missing_override; + selected = nullptr; + } + } else if (!candidates.empty()) { + selected = candidates.front(); + reason = SelectionReason::fallback; + if (editor && editor->provider == generation->identity().provider) { + const auto match = std::ranges::find_if(candidates, [&](auto candidate) { + return editor_matches(*editor, candidate->key); + }); + if (match != candidates.end()) { + reason = SelectionReason::editor; + selected = *match; + } + } + } + current_ = Selection{new ContextSelection(scope_, std::move(generation), + current_ ? current_->revision + 1 : 1, file_override, + editor, reason, selected)}; + return current_; +} + +AnalysisRevision::AnalysisRevision(Selection selection, AnalysisInputs inputs) + : selection(std::move(selection)), inputs(std::move(inputs)), + readiness_(assess(*this->selection, this->inputs)) {} + +std::expected AnalysisRevision::capture(Selection selection, + const AnalysisInputs &observed) { + auto inputs = observed; + if (!selection || !consistent_sources(inputs)) { + return std::unexpected(ModelError::invalid_input); + } + if (inputs.document && inputs.document->identity.canonical_path != selection->scope->file) { + return std::unexpected(ModelError::wrong_scope); + } + if (inputs.translation_unit && + (!selection->selected || + inputs.translation_unit->identity.canonical_path != selection->selected->key.owning_tu)) { + return std::unexpected(ModelError::wrong_scope); + } + if (!inputs.translation_unit && selection->selected && + selection->scope->file == selection->selected->key.owning_tu) { + inputs.translation_unit = inputs.document; + } + if (inputs.backend && + (!identifier(inputs.backend->implementation) || !identifier(inputs.backend->version) || + !identifier(inputs.backend->protocol))) { + return std::unexpected(ModelError::invalid_identity); + } + if (inputs.rename) { + if (auto valid = validate_coverage(*inputs.rename, *selection); !valid) { + return std::unexpected(valid.error()); + } + } + return Revision{new AnalysisRevision(std::move(selection), std::move(inputs))}; +} + +const Readiness &AnalysisRevision::readiness(Operation operation) const { + const auto index = static_cast(operation); + if (index >= readiness_.size()) { + static const Readiness unavailable{ReadinessLevel::unavailable, {}}; + return unavailable; + } + return readiness_[index]; +} + +bool AnalysisRevision::same_input_as(const AnalysisRevision &other) const { + return this == &other || + (selection == other.selection && inputs.lookup_epoch == other.inputs.lookup_epoch && + inputs.configuration_generation == other.inputs.configuration_generation && + inputs.trust_generation == other.inputs.trust_generation && + inputs.backend == other.inputs.backend && inputs.rename == other.inputs.rename && + same_source(inputs.document, other.inputs.document) && + same_source(inputs.translation_unit, other.inputs.translation_unit) && + same_dependencies(inputs.dependencies, other.inputs.dependencies)); +} + +PublicationSlot::PublicationSlot(const SelectionState &selection, Operation operation) + : scope_(selection.scope()), operation_(operation) {} + +std::expected PublicationSlot::replace_inputs(std::uint64_t sequence, + Revision revision) { + if (revision && revision->selection->scope != scope_) { + return std::unexpected(ModelError::wrong_scope); + } + State retired; + std::lock_guard lock{mutex_}; + if (sequence <= sequence_) { + return std::unexpected(ModelError::superseded); + } + sequence_ = sequence; + if (revision) { + const auto &inputs = revision->inputs; + if (revision->selection->revision < selection_floor_ || + regresses(inputs.trust_generation, trust_floor_) || + regresses(inputs.configuration_generation, configuration_floor_) || + regresses(inputs.lookup_epoch, lookup_floor_)) { + std::swap(retired, state_); + return std::unexpected(ModelError::superseded); + } + selection_floor_ = revision->selection->revision; + if (inputs.trust_generation) { + trust_floor_ = inputs.trust_generation; + } + if (inputs.configuration_generation) { + configuration_floor_ = inputs.configuration_generation; + } + if (inputs.lookup_epoch) { + lookup_floor_ = inputs.lookup_epoch; + } + if (state_.revision && state_.revision->same_input_as(*revision)) { + return {}; + } + } + // A lease destructor can run provider code. Release displaced owners after unlocking. + std::swap(retired, state_); + state_.revision = std::move(revision); + return {}; +} + +void PublicationSlot::revoke_trust(const WorkspaceIdentity &workspace, + std::uint64_t new_generation) { + if (scope_->workspace != workspace) { + return; + } + State retired; + std::lock_guard lock{mutex_}; + if (trust_floor_ && new_generation <= *trust_floor_) { + return; + } + trust_floor_ = new_generation; + std::swap(retired, state_); +} + +std::expected PublicationSlot::issue() { + std::lock_guard lock{mutex_}; + if (!state_.revision) { + return std::unexpected(ModelError::no_inputs); + } + if (state_.revision->readiness(operation_).level == ReadinessLevel::unavailable) { + return std::unexpected(ModelError::operation_unavailable); + } + if (last_request_ == std::numeric_limits::max()) { + return std::unexpected(ModelError::sequence_exhausted); + } + state_.pending = + std::make_shared(++last_request_, operation_, state_.revision); + return state_.pending; +} + +bool PublicationSlot::cancel(const Ticket &ticket) { + std::lock_guard lock{mutex_}; + if (!ticket || state_.pending != ticket) { + return false; + } + state_.pending.reset(); + return true; +} + +bool PublicationSlot::publish(const Ticket &ticket, std::string_view validated_payload) { + if (!ticket) { + return false; + } + auto result = std::make_shared(ticket, std::string{validated_payload}); + std::lock_guard lock{mutex_}; + if (state_.pending != ticket) { + return false; + } + state_.published.swap(result); + state_.pending.reset(); + return true; +} + +std::shared_ptr PublicationSlot::current() const { + std::lock_guard lock{mutex_}; + return state_.published; +} +} // namespace Void::LanguageServer::Build diff --git a/src/Build/ProviderFile.cpp b/src/Build/ProviderFile.cpp new file mode 100644 index 0000000..a35d716 --- /dev/null +++ b/src/Build/ProviderFile.cpp @@ -0,0 +1,522 @@ +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace Void::LanguageServer::Build { +namespace fs = std::filesystem; +using System::OwnedFd; + +namespace { +struct Directory { + fs::path path; + OwnedFd fd; + struct stat identity; +}; +using Anchor = std::shared_ptr; + +bool same_inode(const struct stat &a, const struct stat &b) { + return a.st_dev == b.st_dev && a.st_ino == b.st_ino; +} + +bool normalized(const fs::path &path) { + return Detail::valid_path(path) && path.is_absolute() && path == path.lexically_normal() && + (path == path.root_path() || path.has_filename()); +} + +bool below(const fs::path &path, const fs::path &root) { + const auto [r, p] = std::mismatch(root.begin(), root.end(), path.begin(), path.end()); + return r == root.end() && p != path.end(); +} + +OwnedFd open_direct(int parent, const fs::path &path, int flags, bool beneath) { + open_how how{}; + how.flags = static_cast(flags | O_PATH | O_CLOEXEC); + how.resolve = RESOLVE_NO_SYMLINKS | RESOLVE_NO_MAGICLINKS; + if (beneath) + how.resolve |= RESOLVE_BENEATH; + return OwnedFd{ + static_cast(::syscall(SYS_openat2, parent, path.c_str(), &how, sizeof how))}; +} + +ProviderIssue open_error(int code, FilePurpose purpose, const fs::path &path) { + if (code == ENOENT) { + const bool required = + purpose == FilePurpose::status || purpose == FilePurpose::native_database; + return {required ? "missing_reference" : "missing", "Metadata path is absent", path}; + } + if (code == ELOOP || code == EXDEV) + return {"outside_scope", "Path follows a disallowed link or leaves the selected directory", + path}; + if (code == EAGAIN || code == ESTALE) + return {"changed", "Path changed during lookup", path}; + return {"unavailable", "Cannot open the admitted path", path}; +} + +std::expected bind_directory(const fs::path &path) { + if (!normalized(path)) + return std::unexpected( + ProviderIssue{"invalid_path", "Expected a normalized absolute directory", path}); + auto fd = open_direct(AT_FDCWD, path, O_DIRECTORY, false); + struct stat state{}; + if (!fd || ::fstat(fd.get(), &state) != 0) + return std::unexpected( + ProviderIssue{"unavailable", "Cannot bind the selected directory", path}); + return std::make_shared(path, std::move(fd), state); +} + +bool directory_current(const Anchor &anchor) { + auto named = open_direct(AT_FDCWD, anchor->path, O_DIRECTORY, false); + struct stat state{}; + return named && ::fstat(named.get(), &state) == 0 && same_inode(anchor->identity, state); +} + +bool native_locator(const fs::path &path, const fs::path &anchor, bool exact_root, + FilePurpose purpose) { + auto editor = path.parent_path(); + if (purpose == FilePurpose::native_database) { + const auto id = editor.filename().native(); + if (path.filename() != "compile_commands.json" || id.size() != 16 || + id.find_first_not_of("0123456789abcdef") != id.npos || + editor.parent_path().filename() != "generations") + return false; + editor = editor.parent_path().parent_path(); + } else if (path.filename() != "status.json") { + return false; + } + const auto profile = editor.parent_path(); + const auto profiles = profile.parent_path(); + const auto component = profile.filename().native(); + if (editor.filename() != "editor" || profiles.filename() != "profiles" || component.empty() || + component.size() > 255 || + component.find_first_not_of( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-") != component.npos) + return false; + const auto root = profiles.parent_path(); + return root == anchor || (!exact_root && below(root, anchor)); +} + +struct Route { + Anchor anchor; + bool permit_leaf_link{}; +}; +struct OpenedFile { + OwnedFd object, link; + fs::path canonical; + struct stat metadata{}, parent{}; + std::optional link_state; +}; +} // namespace + +struct ProviderAnchors { + ProviderScope requested; // Captured before installing the shared anchors in the returned scope. + // A failed optional grant stays failed for its lifetime, even if the name later appears. + std::map> directories; +}; +struct ProviderStamp { + std::shared_ptr anchors; + FilePurpose purpose; + fs::path logical; + OpenedFile file; +}; +struct CommandPathStamp { + std::shared_ptr anchors; + CommandPathKind kind; + std::pair object{}; + std::vector> links; + bool operator==(const CommandPathStamp &) const = default; +}; + +std::expected bind_provider_scope(ProviderScope scope) { + if (scope.anchors || scope.workspace.session.empty() || !normalized(scope.workspace.root)) + return std::unexpected( + ProviderIssue{"invalid_path", "Invalid workspace binding", scope.workspace.root}); + auto binding = std::make_shared(); + binding->requested = scope; + auto add = [&](const fs::path &path) -> const std::expected & { + auto [it, fresh] = binding->directories.try_emplace(path); + if (fresh) + it->second = bind_directory(path); + return it->second; + }; + if (auto owner = add(scope.workspace.root); !owner) + return std::unexpected(std::move(owner.error())); + if (scope.build_root) + add(*scope.build_root); + for (const auto *grant : {&scope.exact_selector, &scope.exact_database}) { + if (!*grant) + continue; + const auto &file = **grant; + // route_for validates the spelling when the locator is actually used. + // An unusable optional locator cannot invalidate the workspace binding. + if (normalized(file) && file.has_filename() && !below(file, scope.workspace.root)) + add(file.parent_path()); + } + scope.anchors = std::move(binding); + return scope; +} + +std::expected reuse_provider_scope(const ProviderScope &bound, + std::string new_session) { + if (!bound.anchors || new_session.empty() || new_session.contains('\0')) + return std::unexpected( + ProviderIssue{"invalid_path", "Invalid workspace incarnation", bound.workspace.root}); + const auto &root = bound.anchors->requested.workspace.root; + if (!directory_current(*bound.anchors->directories.at(root))) + return std::unexpected(ProviderIssue{"changed", "The workspace directory was replaced", root}); + auto anchors = std::make_shared(*bound.anchors); + anchors->requested.workspace.session = std::move(new_session); + auto scope = anchors->requested; + scope.anchors = std::move(anchors); + return scope; +} + +namespace { +std::expected workspace_anchor(const ProviderScope &scope, const fs::path &path) { + if (!scope.anchors) + return std::unexpected( + ProviderIssue{"invalid_path", "Unbound workspace scope", path}); + const auto &bound = scope.anchors->requested; + if (scope.workspace != bound.workspace || scope.exact_database != bound.exact_database || + scope.exact_selector != bound.exact_selector || scope.build_root != bound.build_root || + scope.producer_cwd != bound.producer_cwd) + return std::unexpected(ProviderIssue{"outside_scope", "Metadata grant has changed", path}); + const auto workspace = *scope.anchors->directories.at(bound.workspace.root); + if (!directory_current(workspace)) + return std::unexpected( + ProviderIssue{"changed", "Workspace directory was replaced", path}); + return workspace; +} + +std::expected route_for(const ProviderScope &scope, const fs::path &path, + FilePurpose purpose) { + if (!normalized(path) || !path.has_filename()) + return std::unexpected(ProviderIssue{"invalid_path", "Invalid metadata path", path}); + const auto owner = workspace_anchor(scope, path); + if (!owner) + return std::unexpected(owner.error()); + const auto &workspace = *owner; + const auto &bound = scope.anchors->requested; + const bool native = purpose == FilePurpose::status || purpose == FilePurpose::native_database; + const fs::path *authority = &workspace->path; + bool leaf_link = false; + if (native) { + if (bound.build_root) + authority = &*bound.build_root; + if (!native_locator(path, *authority, bound.build_root.has_value(), purpose)) + return std::unexpected( + ProviderIssue{"outside_scope", "Invalid native generation locator", path}); + } else if (below(path, workspace->path)) { + leaf_link = purpose == FilePurpose::database || purpose == FilePurpose::response; + } else if ((purpose == FilePurpose::database && bound.exact_database == path) || + (purpose == FilePurpose::selection && bound.exact_selector == path)) { + const auto &anchor = scope.anchors->directories.at(path.parent_path()); + if (!anchor) + return std::unexpected(ProviderIssue{anchor.error().code, anchor.error().message, path}); + if (!directory_current(*anchor)) + return std::unexpected( + ProviderIssue{"changed", "Selected metadata directory was replaced", path}); + return Route{*anchor, false}; + } else { + return std::unexpected( + ProviderIssue{"outside_scope", "Path is outside this workspace grant", path}); + } + const auto &anchor = scope.anchors->directories.at(*authority); + if (!anchor) + return std::unexpected(ProviderIssue{anchor.error().code, anchor.error().message, path}); + if (*anchor != workspace && !directory_current(*anchor)) + return std::unexpected( + ProviderIssue{"changed", "Selected build directory was replaced", path}); + return Route{*anchor, leaf_link}; +} + +// A link may backtrack through the already verified containing directory. +// A later '..' would need to traverse additional, unverified components. +std::optional link_target(int link, const fs::path &logical, const fs::path &root, + bool allow_root = false) { + std::array name{}; + const auto size = ::readlinkat(link, "", name.data(), name.size()); + if (size <= 0 || static_cast(size) == name.size()) + return {}; + const fs::path target{std::string{name.data(), static_cast(size)}}; + bool descending = target.is_absolute(); + for (const auto &part : target) { + if (part == ".." && descending) + return {}; + if (part != ".." && part != ".") + descending = true; + } + const auto resolved = (logical.parent_path() / target).lexically_normal(); + if (!normalized(resolved) || (!below(resolved, root) && !(allow_root && resolved == root))) + return {}; + return resolved; +} + +std::expected open_file(const Route &route, const fs::path &path, + FilePurpose purpose) { + const auto parent_name = path.parent_path().lexically_relative(route.anchor->path); + auto parent = open_direct(route.anchor->fd.get(), parent_name, O_DIRECTORY, true); + if (!parent) + return std::unexpected(open_error(errno, purpose, path)); + OpenedFile result; + if (::fstat(parent.get(), &result.parent) != 0) + return std::unexpected( + ProviderIssue{"unavailable", "Cannot identify metadata directory", path}); + result.object = open_direct(parent.get(), path.filename(), O_NOFOLLOW, true); + if (!result.object) + return std::unexpected(open_error(errno, purpose, path)); + if (::fstat(result.object.get(), &result.metadata) != 0) + return std::unexpected(ProviderIssue{"unavailable", "Cannot identify metadata file", path}); + result.canonical = path; + if (S_ISLNK(result.metadata.st_mode)) { + if (!route.permit_leaf_link) + return std::unexpected( + ProviderIssue{"outside_scope", "This locator must be a direct file", path}); + const auto target = link_target(result.object.get(), path, route.anchor->path); + if (!target) + return std::unexpected( + ProviderIssue{"outside_scope", "Link target is outside the admitted path", path}); + result.link_state = result.metadata; + result.link = std::move(result.object); + result.object = open_direct(route.anchor->fd.get(), + target->lexically_relative(route.anchor->path), 0, true); + if (!result.object || ::fstat(result.object.get(), &result.metadata) != 0) + return std::unexpected(ProviderIssue{ + "unavailable", "Cannot resolve metadata link to a direct file", path}); + result.canonical = *target; + } + if (!S_ISREG(result.metadata.st_mode)) + return std::unexpected( + ProviderIssue{"not_regular", "Metadata must be a regular file", path}); + return result; +} + +std::size_t allowed_bytes(const Workspace::ResourceLimitsConfig &limits, FilePurpose purpose) { + if (purpose == FilePurpose::response) + return limits.max_response_file_bytes; + if (purpose == FilePurpose::database || purpose == FilePurpose::native_database) + return limits.max_compdb_bytes; + return limits.max_manifest_bytes; +} + +bool same_capture(const OpenedFile &a, const OpenedFile &b) { + return a.canonical == b.canonical && same_inode(a.parent, b.parent) && + Detail::same_file_state(a.metadata, b.metadata) && + a.link_state.has_value() == b.link_state.has_value() && + (!a.link_state || Detail::same_file_state(*a.link_state, *b.link_state)); +} + +struct PathResult { + fs::path physical; + std::string issue; +}; + +bool expected_kind(const struct stat &state, CommandPathKind kind) { + return kind == CommandPathKind::directory ? S_ISDIR(state.st_mode) : S_ISREG(state.st_mode); +} + +// Open every name beneath the original root descriptor. Never follow a kernel symlink +// or descend from a directory descriptor that may since have moved outside the root. +struct CommandPathWalk { + const Directory &root; + CommandPathStamp &stamp; + unsigned steps{}; + + PathResult resolve(const fs::path &path, CommandPathKind kind, bool require_present = false) { + const auto relative = path.lexically_relative(root.path); + // Ordinary direct paths, including prospective generated inputs, take one lookup. + if (normalized(path)) { + auto file = open_direct(root.fd.get(), relative, O_NOFOLLOW, true); + struct stat state{}; + if (file) { + if (::fstat(file.get(), &state) != 0) + return {{}, "unavailable"}; + if (!S_ISLNK(state.st_mode)) { + stamp.object = {state.st_dev, state.st_ino}; + return expected_kind(state, kind) ? PathResult{path, {}} : PathResult{{}, "wrong_kind"}; + } + } else if (errno != ELOOP) { + const int error = errno; + if (error == ENOENT && !require_present) + return {path, "missing"}; + return {{}, error == ENOENT ? "unavailable" : open_error(error, FilePurpose::response, path).code}; + } + } + fs::path current = root.path; + bool missing = false; + for (auto it = relative.begin(); it != relative.end(); ++it) { + if (++steps > 256) + return {{}, "path_limit"}; + if (it->empty() || *it == ".") + continue; + if (*it == "..") { + if (current == root.path || missing) + return {{}, "unresolved_parent"}; + current = current.parent_path(); + continue; + } + current /= *it; + if (!Detail::valid_path(current)) + return {{}, "path_limit"}; + if (missing) + continue; + const auto required = std::next(it) == relative.end() ? kind : CommandPathKind::directory; + auto fd = open_direct(root.fd.get(), current.lexically_relative(root.path), O_NOFOLLOW, true); + if (!fd) { + const int error = errno; + if (error == ENOENT && !require_present) { + missing = true; + continue; + } + return {{}, error == ENOENT ? "unavailable" : open_error(error, FilePurpose::response, current).code}; + } + struct stat state{}; + if (::fstat(fd.get(), &state) != 0) + return {{}, "unavailable"}; + stamp.object = {state.st_dev, state.st_ino}; + if (S_ISLNK(state.st_mode)) { + if (stamp.links.size() == 16) + return {{}, "link_limit"}; + stamp.links.emplace_back(state.st_dev, state.st_ino, state.st_ctim.tv_sec, state.st_ctim.tv_nsec); + auto target = link_target(fd.get(), current, root.path, required == CommandPathKind::directory); + if (!target) + return {{}, "outside_scope"}; + auto resolved = resolve(*target, required, true); + if (resolved.physical.empty()) + return resolved; + current = std::move(resolved.physical); + } else if (!expected_kind(state, required)) { + return {{}, "wrong_kind"}; + } + } + return {std::move(current), missing ? "missing" : ""}; + } +}; + +bool failed_response_current(const ProviderScope &scope, const FailedResponseLookup &failed) { + const auto &issue = failed.issue; + const auto purpose = FilePurpose::response; + auto route = route_for(scope, issue.path, purpose); + if (!route) + return route.error().code == issue.code; + auto fresh = open_file(*route, issue.path, purpose); + if (!fresh) + return fresh.error().code == issue.code; + const auto limit = std::min({failed.byte_limit, allowed_bytes(scope.limits, purpose), + allowed_bytes(scope.anchors->requested.limits, purpose)}); + if (fresh->metadata.st_size < 0 || static_cast(fresh->metadata.st_size) > limit) + return issue.code == "too_large"; + // Permission failures can persist on a regular file. A successful namespace probe of a + // previously absent/refused name invalidates that observation without reading its contents. + return issue.code == "unavailable" && + ::faccessat(fresh->object.get(), "", R_OK, AT_EMPTY_PATH | AT_EACCESS) != 0; +} +} // namespace + +CommandPathLookup inspect_command_path(const ProviderScope &scope, const fs::path &path, + CommandPathKind kind) { + auto stamp = std::make_shared(scope.anchors, kind); + auto owner = workspace_anchor(scope, path); + if (!owner) + return {path, {}, owner.error().code, std::move(stamp)}; + const auto &root = (*owner)->path; + if (!Detail::valid_path(path) || (path != root && !below(path, root))) + return {path, {}, "outside_scope", std::move(stamp)}; + auto result = CommandPathWalk{**owner, *stamp}.resolve(path, kind); + return {path, std::move(result.physical), std::move(result.issue), std::move(stamp)}; +} + +std::optional changed_provider_input(const ProviderScope &scope, + const ProviderObservation &observation) { + for (const auto &file : observation.inputs) + if (!provider_file_current(scope, file)) + return file.logical_path; + for (const auto &path : observation.lookups.paths) { + if (!path.stamp || path.stamp->anchors != scope.anchors || path.issue == "changed") + return path.logical_path; + const auto fresh = inspect_command_path(scope, path.logical_path, path.stamp->kind); + if (fresh.issue != path.issue || fresh.physical_path != path.physical_path || *fresh.stamp != *path.stamp) + return path.logical_path; + } + for (const auto &failed : observation.lookups.failed_responses) + if (!failed_response_current(scope, failed)) + return failed.issue.path; + return {}; +} + +bool provider_file_current(const ProviderScope &scope, const ProviderFile &file) { + if (!file.stamp || file.stamp->anchors != scope.anchors || + file.stamp->purpose != file.purpose || file.stamp->logical != file.logical_path || + file.stamp->file.canonical != file.canonical_path) + return false; + const auto route = route_for(scope, file.logical_path, file.purpose); + if (!route) + return false; + auto fresh = open_file(*route, file.logical_path, file.purpose); + return fresh && same_capture(*fresh, file.stamp->file); +} + +bool same_provider_object(const ProviderFile &a, const ProviderFile &b) noexcept { + return a.stamp && b.stamp && same_inode(a.stamp->file.metadata, b.stamp->file.metadata); +} + +std::expected read_provider_file(const ProviderScope &scope, + const fs::path &path, + FilePurpose purpose, + std::size_t byte_limit) { + auto route = route_for(scope, path, purpose); + if (!route) + return std::unexpected(std::move(route.error())); + auto file = open_file(*route, path, purpose); + if (!file) + return std::unexpected(std::move(file.error())); + const auto limit = std::min({byte_limit, allowed_bytes(scope.limits, purpose), + allowed_bytes(scope.anchors->requested.limits, purpose)}); + if (file->metadata.st_size < 0 || static_cast(file->metadata.st_size) > limit) + return std::unexpected(ProviderIssue{"too_large", "Metadata exceeds its byte limit", path}); + auto data = std::make_shared(); + data->reserve(static_cast(file->metadata.st_size)); + auto hash = Crypto::Hasher::create(Crypto::HashAlgorithm::Sha256); + if (!hash) + return std::unexpected(ProviderIssue{"unavailable", "Cannot create metadata digest", path}); + auto read = + Detail::stream_regular_fd(file->object, file->metadata, limit, false, [&](auto chunk) { + data->append(reinterpret_cast(chunk.data()), chunk.size()); + return hash->update(chunk).has_value(); + }); + if (!read) + return std::unexpected( + ProviderIssue{read.error() == Detail::FileError::changed ? "changed" : "unavailable", + "Could not capture a stable metadata file", path}); + auto digest = hash->finalize(); + if (!digest || digest->size() != 32) + return std::unexpected( + ProviderIssue{"unavailable", "Cannot finalize metadata digest", path}); + std::string hex; + hex.reserve(64); + constexpr std::string_view digits = "0123456789abcdef"; + for (auto byte : *digest) { + const auto n = std::to_integer(byte); + hex.push_back(digits[n >> 4]); + hex.push_back(digits[n & 15]); + } + const auto stamp = + std::make_shared(scope.anchors, purpose, path, std::move(*file)); + ProviderFile result{purpose, path, stamp->file.canonical, + std::move(data), std::move(hex), stamp}; + if (!provider_file_current(scope, result)) + return std::unexpected( + ProviderIssue{"changed", "Metadata binding changed during capture", path}); + return result; +} +} // namespace Void::LanguageServer::Build diff --git a/src/Build/VbsProvider.cpp b/src/Build/VbsProvider.cpp new file mode 100644 index 0000000..a11a61a --- /dev/null +++ b/src/Build/VbsProvider.cpp @@ -0,0 +1,272 @@ +#include +#include + +#include +#include +#include + +namespace Void::LanguageServer::Build { +namespace { +namespace fs = std::filesystem; +using Protocol::Json; + +const std::string *text_field(const Json::Object &object, std::string_view key) { + return Protocol::as_string(Protocol::find_member(object, key)); +} + +std::optional unsigned_field(const Json::Object &object, std::string_view key) { + const auto *value = Protocol::find_member(object, key); + const auto *integer = value ? std::get_if(&value->value) : nullptr; + if (!integer || *integer < 0) + return {}; + return static_cast(*integer); +} + +bool valid_component_text(std::string_view value) { + return !value.empty() && value.size() <= 255 && !value.contains('\0'); +} + +std::string profile_directory(std::string_view profile) { + std::string slug{profile}; + for (auto &c : slug) { + const bool alphanumeric = + (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); + if (!alphanumeric && c != '.' && c != '_' && c != '-') + c = '_'; + } + return slug; +} + +bool generation_id(std::string_view id) { + return id.size() == 16 && id.find_first_not_of("0123456789abcdef") == id.npos; +} + +enum class LocatorKind { directory, file }; + +std::optional locator(std::string_view value, LocatorKind kind) { + if (value.empty() || value.size() > 4095 || value.contains('\0')) + return {}; + fs::path path{value}; + if (kind == LocatorKind::file && (!path.has_filename() || path.filename() == ".")) + return {}; + if (std::find(path.begin(), path.end(), fs::path{".."}) != path.end()) + return {}; + path = path.lexically_normal(); + if (path != path.root_path() && !path.has_filename()) + path = path.parent_path(); + return path; +} + +bool has_suffix(const fs::path &absolute, const fs::path &relative) { + if (relative == ".") + return true; + auto name = absolute.end(); + for (auto part = relative.end(); part != relative.begin();) { + if (name == absolute.begin() || *--name != *--part) + return false; + } + return true; +} + +bool usable_producer_cwd(const fs::path &path) { + return path.is_absolute() && path == path.lexically_normal() && + path.native().find('\0') == std::string::npos; +} + +std::optional resolve_root(const ProviderScope &scope, const fs::path &producer_root) { + std::optional absolute; + if (producer_root.is_absolute()) + absolute = producer_root; + else if (scope.producer_cwd) { + if (usable_producer_cwd(*scope.producer_cwd)) + absolute = locator((*scope.producer_cwd / producer_root).native(), LocatorKind::directory); + } + else if (scope.build_root && has_suffix(*scope.build_root, producer_root)) + absolute = scope.build_root; + if (absolute && scope.build_root && *absolute != *scope.build_root) + return {}; + return absolute; +} + +bool points_to_generation(const ProviderScope &scope, const fs::path &producer_root, + const fs::path &pointer, const fs::path &root, const fs::path &suffix) { + const auto expected = root / suffix; + if (pointer.is_absolute()) + return pointer == expected; + if (scope.producer_cwd) + return usable_producer_cwd(*scope.producer_cwd) && + (*scope.producer_cwd / pointer).lexically_normal() == expected; + if (!scope.build_root) + return false; + if (producer_root.is_relative()) + return pointer == (producer_root / suffix).lexically_normal(); + return has_suffix(pointer, suffix) && has_suffix(expected, pointer); +} + +std::expected read_pointer(const ProviderScope &scope, + const fs::path &path, FilePurpose purpose, + ProviderObservation &observation) { + constexpr std::size_t pointer_cap = 256 * 1024; + auto file = read_provider_file(scope, path, purpose, + std::min(scope.limits.max_manifest_bytes, pointer_cap)); + if (!file) + return std::unexpected(std::move(file.error())); + observation.inputs.push_back(std::move(*file)); + auto parsed = Protocol::parse_json(*observation.inputs.back().bytes, 12); + auto *object = parsed ? std::get_if(&parsed->value) : nullptr; + if (!object) + return std::unexpected( + ProviderIssue{"invalid_metadata", "Expected a VBS metadata object", path}); + if (unsigned_field(*object, "schema_version") != 1) + return std::unexpected( + ProviderIssue{"unsupported_schema", "Expected VBS editor schema version 1", path}); + return std::move(*object); +} + +ProviderHealth read_health(const ProviderIssue &issue, bool selector = false) { + if (issue.code == "changed") + return ProviderHealth::changed; + if (issue.code == "missing" && selector) + return ProviderHealth::missing; + if (issue.code == "invalid_metadata" || issue.code == "unsupported_schema") + return ProviderHealth::invalid; + return ProviderHealth::unavailable; +} + +ProviderObservation read_vbs(const ProviderScope &scope, const fs::path &selector, + const std::optional &driver) { + ProviderObservation result{.provider = "vbs"}; + auto fail = [&](ProviderHealth health, ProviderIssue issue) { + result.health = health; + result.issues.push_back(std::move(issue)); + return std::move(result); + }; + + const auto selection = read_pointer(scope, selector, FilePurpose::selection, result); + if (!selection) + return fail(read_health(selection.error(), true), selection.error()); + const auto *profile = text_field(*selection, "selected_profile"); + const auto *build = text_field(*selection, "selected_build_root"); + const auto *id = text_field(*selection, "selected_generation_id"); + const auto *selected_db = text_field(*selection, "selected_compdb_path"); + result.selection_ticket = unsigned_field(*selection, "ticket"); + if (!result.selection_ticket || !profile || !build || !id || !selected_db) + return fail(ProviderHealth::invalid, + {"invalid_selection", "Incomplete VBS selection record", selector}); + if (!profile->empty() && valid_component_text(*profile)) + result.profile = *profile; + if (id->empty() && selected_db->empty()) + return fail(ProviderHealth::unavailable, + {"selection_pending", "VBS has not selected a generation yet", selector}); + if (!result.profile || !generation_id(*id)) + return fail(ProviderHealth::invalid, + {"invalid_selection", "Invalid VBS profile or generation ID", selector}); + result.native_generation = *id; + const auto slug = profile_directory(*profile); + if (slug == "." || slug == "..") + return fail(ProviderHealth::invalid, + {"invalid_profile", "Invalid VBS profile directory", selector}); + if (const auto *warning = text_field(*selection, "root_alias_warning"); + warning && !warning->empty()) + result.warnings.push_back({"alias_warning", warning->substr(0, 2048), selector}); + + const auto spelling = locator(*build, LocatorKind::directory); + const auto selected = locator(*selected_db, LocatorKind::file); + if (!spelling || !selected) + return fail(ProviderHealth::invalid, {"invalid_locator", "Invalid VBS locator", selector}); + const auto root = resolve_root(scope, *spelling); + if (!root) + return fail(ProviderHealth::unavailable, + {"ambiguous_locator", "Cannot bind the selected VBS build root", selector}); + const auto editor = fs::path{"profiles"} / slug / "editor"; + const auto suffix = editor / "generations" / *id / "compile_commands.json"; + if (!points_to_generation(scope, *spelling, *selected, *root, suffix)) + return fail(ProviderHealth::invalid, + {"locator_mismatch", "Selected path does not identify the immutable generation", + selector}); + + const auto status_path = *root / editor / "status.json"; + const auto status = read_pointer(scope, status_path, FilePurpose::status, result); + if (!status) + return fail(read_health(status.error()), status.error()); + const auto *status_profile = text_field(*status, "profile"); + const auto *state = text_field(*status, "status"); + const auto *diagnostic = text_field(*status, "diagnostic"); + if (!status_profile || *status_profile != *profile || !state || !diagnostic) + return fail(ProviderHealth::invalid, + {"invalid_status", "Incomplete or mismatched VBS profile status", status_path}); + if (*state == "stale" || *state == "invalid") + return fail(*state == "stale" ? ProviderHealth::stale : ProviderHealth::invalid, + {"vbs_" + *state, + diagnostic->empty() ? "VBS marked the generation " + *state + : diagnostic->substr(0, 2048), + status_path}); + const auto *status_id = text_field(*status, "generation_id"); + const auto *db_text = text_field(*status, "compdb_path"); + const auto status_db = db_text ? locator(*db_text, LocatorKind::file) : std::nullopt; + const auto count = unsigned_field(*status, "entry_count"); + const auto *warnings = Protocol::as_array(Protocol::find_member(*status, "readiness_warnings")); + if (*state != "valid" || !status_id || !generation_id(*status_id) || !status_db || !count || + !warnings) + return fail(ProviderHealth::invalid, + {"invalid_status", "Invalid VBS valid-generation record", status_path}); + if (*status_id != *id || !points_to_generation(scope, *spelling, *status_db, *root, suffix)) + return fail(ProviderHealth::changed, + {"generation_mismatch", + "VBS selection and profile status refer to different generations", + status_path}); + if (warnings->size() > 256) + return fail(ProviderHealth::invalid, + {"too_large", "Too many VBS readiness warnings", status_path}); + for (const auto &warning : *warnings) { + const auto *message = Protocol::as_string(&warning); + if (!message || message->size() > 2048) + return fail(ProviderHealth::invalid, + {"invalid_status", "Invalid VBS readiness warning", status_path}); + result.warnings.push_back({"readiness_warning", *message, status_path}); + } + + const auto path = *root / suffix; + auto file = read_provider_file(scope, path, FilePurpose::native_database, + scope.limits.max_compdb_bytes); + if (!file) + return fail(read_health(file.error()), file.error()); + result.inputs.push_back(std::move(*file)); + auto imported = import_commands({scope, result.inputs.back(), result.profile, driver}); + if (!imported) + return fail(ProviderHealth::invalid, std::move(imported.error())); + if (imported->contexts.size() != *count) + return fail(ProviderHealth::invalid, + {"count_mismatch", "VBS entry_count differs from its database", path}); + + // Length-prefix the variable locator. Native IDs describe producer state; + // the byte identities also distinguish in-place DB repairs and response edits. + auto revision = std::to_string(path.native().size()) + "/" + path.native() + "/" + *id + "/" + + result.inputs[1].content_id + "/" + result.inputs.back().content_id + "/" + + imported->revision; + auto generation = + BuildGeneration::create({scope.workspace, "vbs", std::move(revision)}, imported->contexts); + if (!generation) + return fail(ProviderHealth::invalid, + {"invalid_context", "Invalid native compilation context", path}); + result.inputs.insert(result.inputs.end(), + std::make_move_iterator(imported->dependencies.begin()), + std::make_move_iterator(imported->dependencies.end())); + result.lookups = std::move(imported->lookups); + result.generation = std::move(*generation); + result.health = ProviderHealth::ready; + return result; +} +} // namespace + +ProviderObservation observe_vbs(const ProviderScope &scope, const fs::path &selector, + const std::optional &driver) { + auto result = read_vbs(scope, selector, driver); + if (auto changed = changed_provider_input(scope, result)) { + result.health = ProviderHealth::changed; + result.generation.reset(); + result.issues = {{"changed", "VBS inputs changed during observation", *changed}}; + } + return result; +} +} // namespace Void::LanguageServer::Build diff --git a/src/DocumentSync.cpp b/src/DocumentSync.cpp new file mode 100644 index 0000000..cc787b1 --- /dev/null +++ b/src/DocumentSync.cpp @@ -0,0 +1,136 @@ +#include + +#include + +namespace vls { +namespace { + +namespace Docs = Void::LanguageServer::Documents; +namespace Protocol = Void::LanguageServer::Protocol; +using Protocol::Json; + +const Json *field(const Json *value, std::string_view key) { + const auto *object = Protocol::as_object(value); + return object ? Protocol::find_member(*object, key) : nullptr; +} + +std::optional integer(const Json *value) { + const auto number = Protocol::as_int64(value); + if (!number || !std::in_range(*number)) + return std::nullopt; + return static_cast(*number); +} + +std::optional uinteger(const Json *value) { + const auto number = integer(value); + if (!number || *number < 0) + return std::nullopt; + return static_cast(*number); +} + +std::optional position(const Json *value) { + const auto line = uinteger(field(value, "line")); + const auto character = uinteger(field(value, "character")); + if (!line || !character) + return std::nullopt; + return Docs::Position{*line, *character}; +} + +std::expected decode_edit(const Json &change) { + const auto *text = Protocol::as_string(field(&change, "text")); + if (!text) + return std::unexpected{"change requires text"}; + const auto *range = field(&change, "range"); + const auto *length = field(&change, "rangeLength"); + if (length && (!range || !uinteger(length))) + return std::unexpected{"invalid change rangeLength"}; + if (!range) + return Docs::TextEdit{std::nullopt, *text}; + const auto start = position(field(range, "start")); + const auto end = position(field(range, "end")); + if (!start || !end) + return std::unexpected{"invalid change range"}; + return Docs::TextEdit{Docs::Range{*start, *end}, *text}; +} + +std::expected apply_change(Docs::DocumentStore &store, const std::string &uri, + const Json *document, const Json *params) { + const auto version = integer(field(document, "version")); + const auto reject = [&](std::string_view why) -> std::expected { + auto marked = store.mark_desynchronized( + uri, version, {Docs::DocumentError::Kind::malformed_change, std::string{why}}); + return std::unexpected{marked ? std::string{why} : std::move(marked.error().message)}; + }; + if (!version) + return reject("invalid change version"); + const auto *changes = Protocol::as_array(field(params, "contentChanges")); + if (!changes || changes->size() > Docs::DocumentLimits{}.max_changes) + return reject("invalid contentChanges array or too many changes"); + std::vector edits; + edits.reserve(changes->size()); + for (const auto &change : *changes) { + auto edit = decode_edit(change); + if (!edit) + return reject(edit.error()); + edits.push_back(std::move(*edit)); + } + auto applied = store.apply_changes(uri, *version, edits); + if (!applied) + return std::unexpected{std::move(applied.error().message)}; + return {}; +} + +} // namespace + +void reject_change_envelope(Docs::DocumentStore &store, const Json *params) { + const auto *document = field(params, "textDocument"); + if (const auto *uri = Protocol::as_string(field(document, "uri"))) { + static_cast(store.mark_desynchronized( + *uri, integer(field(document, "version")), + {Docs::DocumentError::Kind::malformed_change, "invalid didChange envelope"})); + } +} + +Docs::PositionEncoding negotiate_position_encoding(const Json ¶ms) { + const auto *general = field(field(¶ms, "capabilities"), "general"); + if (const auto *encodings = Protocol::as_array(field(general, "positionEncodings"))) { + for (const auto &entry : *encodings) { + const auto *name = Protocol::as_string(&entry); + if (name && *name == "utf-8") + return Docs::PositionEncoding::utf8; + if (name && *name == "utf-16") + return Docs::PositionEncoding::utf16; + } + } + return Docs::PositionEncoding::utf16; +} + +std::expected synchronize_document(Docs::DocumentStore &store, + std::string_view method, const Json *params) { + if (method != "textDocument/didOpen" && method != "textDocument/didChange" && + method != "textDocument/didClose") + return {}; + const auto *document = field(params, "textDocument"); + const auto *uri = Protocol::as_string(field(document, "uri")); + if (!uri) + return std::unexpected{"document notification requires a URI"}; + if (method == "textDocument/didChange") + return apply_change(store, *uri, document, params); + if (method == "textDocument/didClose") { + auto closed = store.close(*uri); + if (!closed) + return std::unexpected{std::move(closed.error().message)}; + return {}; + } + const auto *language = Protocol::as_string(field(document, "languageId")); + const auto *text = Protocol::as_string(field(document, "text")); + const auto version = integer(field(document, "version")); + if (!language || !text || !version) + return std::unexpected{"didOpen requires languageId, text and a signed 32-bit version"}; + auto opened = store.open(*uri, *language, *version, *text); + if (!opened) + return std::unexpected{std::move(opened.error().message)}; + return {}; +} + +} // namespace vls diff --git a/src/Documents/DocumentSnapshot.cpp b/src/Documents/DocumentSnapshot.cpp new file mode 100644 index 0000000..1afebb3 --- /dev/null +++ b/src/Documents/DocumentSnapshot.cpp @@ -0,0 +1,38 @@ +#include + +#include +#include +#include + +#include + +namespace Void::LanguageServer::Documents { +std::string ContentHash::display_digest() const { + if (!sha256_hex.empty()) { + return "sha256:" + sha256_hex; + } + return std::format("fnv1a64:{:016x}", fnv1a64); +} + +ContentHash compute_content_hash(std::string_view text) { + ContentHash result; + result.fnv1a64 = Void::Hash::fnv1a64(text); + if (auto digest = Void::Crypto::sha256(text); digest.has_value()) { + result.sha256_hex = Void::Encoding::Hex::encode(*digest); + } + return result; +} + +bool DocumentSnapshot::same_input_as(const DocumentSnapshot &other) const noexcept { + if (origin != other.origin) { + return false; + } + if (origin == DocumentOrigin::overlay) { + return revision_id == other.revision_id; + } + return identity.canonical_path == other.identity.canonical_path && encoding == other.encoding && + overlay_epoch == other.overlay_epoch && + content_hash.fnv1a64 == other.content_hash.fnv1a64 && text == other.text; +} + +} // namespace Void::LanguageServer::Documents diff --git a/src/Documents/DocumentStore.cpp b/src/Documents/DocumentStore.cpp new file mode 100644 index 0000000..a4941e8 --- /dev/null +++ b/src/Documents/DocumentStore.cpp @@ -0,0 +1,659 @@ +#include + +#include + +#ifndef _WIN32 +#include +#endif + +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Documents { +namespace { + +using Kind = DocumentError::Kind; +constexpr std::size_t kMaxLanguageIdBytes = 1024; +constexpr std::size_t kMaxProblemBytes = 256; +std::atomic next_revision{1}; + +std::unexpected failure(Kind kind, std::string message) { + return std::unexpected{DocumentError{kind, std::move(message)}}; +} + +std::expected +bound_file_identity(std::string_view file_uri, const std::filesystem::path &physical_path) { + auto key = client_uri_key(file_uri); + if (!key) { + return failure(Kind::invalid_uri, std::move(key.error())); + } + if (!key->starts_with("file://") || key->ends_with('/') || key->ends_with("/.") || + key->ends_with("/..")) { + return failure(Kind::invalid_uri, "bound source requires a local file URI with a filename"); + } + if (physical_path.native().size() > kMaxDocumentUriBytes) { + return failure(Kind::resource_limit, "bound physical path exceeds the byte limit"); + } + if (!physical_path.is_absolute() || !physical_path.has_filename() || + physical_path.native() != physical_path.lexically_normal().native()) { + return failure(Kind::invalid_uri, "bound source requires a resolved absolute file path"); + } + const auto utf8 = physical_path.generic_u8string(); + const std::string_view path_bytes{reinterpret_cast(utf8.data()), utf8.size()}; + if (path_bytes.contains('\0') || path_bytes.contains('\\') || + !Void::Unicode::validate_utf8(path_bytes)) { + return failure(Kind::invalid_uri, + "bound physical path cannot be represented as a file URI"); + } + return DocumentIdentity{std::move(*key), std::string{file_uri}, physical_path, true}; +} + +struct SnapshotCharge { + std::shared_ptr total; + std::size_t bytes; + + SnapshotCharge(std::shared_ptr total, std::size_t bytes) + : total(std::move(total)), bytes(bytes) { + this->total->fetch_add(bytes, std::memory_order_relaxed); + } + + SnapshotCharge(const SnapshotCharge &) = delete; + SnapshotCharge &operator=(const SnapshotCharge &) = delete; + + ~SnapshotCharge() { total->fetch_sub(bytes, std::memory_order_relaxed); } +}; + +struct BudgetedSnapshot { + BudgetedSnapshot(const std::shared_ptr &total, std::size_t bytes, + DocumentSnapshot snapshot) + : charge(total, bytes), snapshot(std::move(snapshot)) {} + + // Release the charge after destroying the snapshot's buffers. + SnapshotCharge charge; + DocumentSnapshot snapshot; +}; + +struct DiskImage { + std::string text; +#ifndef _WIN32 + Detail::FileInfo file; +#endif +}; + +std::expected read_regular_file(const std::filesystem::path &path, + std::size_t max_bytes) { +#ifndef _WIN32 + std::string text; + auto file = Detail::read_regular(path, max_bytes, false, [&](std::span chunk) { + text.append(reinterpret_cast(chunk.data()), chunk.size()); + return true; + }); + if (file) + return DiskImage{std::move(text), std::move(*file)}; + if (file.error() == Detail::FileError::too_large) + return failure(Kind::resource_limit, "disk document exceeds the byte limit"); + if (file.error() == Detail::FileError::changed) + return failure(Kind::stale_read, "disk document changed while being read"); + return failure(Kind::disk_read_failed, "cannot read regular disk document"); +#else + return failure(Kind::disk_read_failed, "regular-file document reads are unavailable"); +#endif +} + +} // namespace + +DocumentStore::DocumentStore(PositionEncoding encoding, DocumentLimits limits, + DiskReadObserver after_disk_read) + : limits_(limits), after_disk_read_(std::move(after_disk_read)), + snapshot_bytes_(std::make_shared(0)), encoding_(encoding) {} + +bool DocumentStore::set_position_encoding(PositionEncoding encoding) { + std::unique_lock lock{mutex_}; + if (encoding_ == encoding) { + return true; + } + if (!by_uri_.empty() || unknown_file_open_ || unknown_virtual_open_) { + return false; + } + encoding_ = encoding; + ++overlay_epoch_; + return true; +} + +PositionEncoding DocumentStore::position_encoding() const noexcept { + std::shared_lock lock{mutex_}; + return encoding_; +} + +std::size_t DocumentStore::snapshot_overhead(const DocumentIdentity &identity, + std::string_view language_id) const noexcept { + constexpr std::size_t hash_hex_bytes = 64; + return sizeof(BudgetedSnapshot) + hash_hex_bytes + language_id.size() + + identity.canonical_uri.size() + identity.display_uri.size() + + identity.canonical_path.native().size() * sizeof(std::filesystem::path::value_type); +} + +std::size_t DocumentStore::available_snapshot_bytes() const noexcept { + return limits_.max_snapshot_bytes - snapshot_bytes_->load(std::memory_order_relaxed); +} + +DocumentStore::SnapshotResult DocumentStore::make_snapshot(const DocumentIdentity &identity, + std::string_view language_id, + std::optional version, + std::string text, + std::optional index) const { + // All acquisitions run under the store's exclusive lock. References may release their + // charge from another thread or after the store is destroyed. + const auto overhead = snapshot_overhead(identity, language_id); + const auto available = available_snapshot_bytes(); + if (overhead > available || text.capacity() > available - overhead) { + return failure(Kind::resource_limit, "document snapshot memory limit reached"); + } + const auto index_budget = available - overhead - text.capacity(); + if (!index) { + const auto lines = LineIndex::count_lines(text); + if (lines > index_budget / sizeof(std::size_t)) { + return failure(Kind::resource_limit, "document line index exceeds the snapshot budget"); + } + index = LineIndex{text, lines}; + } + if (index->storage_bytes() > index_budget) { + return failure(Kind::resource_limit, "document line index exceeds the snapshot budget"); + } + + const auto bytes = overhead + text.capacity() + index->storage_bytes(); + auto content_hash = compute_content_hash(text); + auto owned = std::make_shared( + snapshot_bytes_, bytes, + DocumentSnapshot{ + .identity = identity, + .language_id = std::string{language_id}, + .version = version, + .revision_id = next_revision.fetch_add(1, std::memory_order_relaxed), + .overlay_epoch = overlay_epoch_, + .text = std::move(text), + .content_hash = std::move(content_hash), + .line_index = std::move(*index), + .encoding = encoding_, + .origin = version ? DocumentOrigin::overlay : DocumentOrigin::disk, + }); + return Snapshot{owned, &owned->snapshot}; +} + +void DocumentStore::desynchronize(OpenDocument &document, const DocumentError &cause) { + document.current.reset(); + document.problem.assign(cause.message, 0, kMaxProblemBytes); +} + +DocumentStore::SnapshotResult DocumentStore::open(std::string_view raw_uri, std::string language_id, + std::int64_t version, std::string text) { + if (!std::in_range(version)) { + return failure(Kind::invalid_version, "open version exceeds the LSP integer range"); + } + if (raw_uri.size() > kMaxDocumentUriBytes) { + std::unique_lock lock{mutex_}; + unknown_file_open_ = true; + ++overlay_epoch_; + return failure(Kind::resource_limit, "document URI exceeds the byte limit"); + } + auto identity = normalize_uri(raw_uri); + if (!identity) { + std::unique_lock lock{mutex_}; + unknown_file_open_ = true; + ++overlay_epoch_; + return failure(Kind::invalid_uri, std::move(identity.error())); + } + + std::unique_lock lock{mutex_}; + if (by_uri_.contains(identity->canonical_uri)) { + return failure(Kind::already_open, "document is already open"); + } + const auto client_version = static_cast(version); + const bool language_id_fits = language_id.size() <= kMaxLanguageIdBytes; + auto admit = [&]() -> SnapshotResult { + if (admitted_documents_ >= limits_.max_open_documents) { + return failure(Kind::resource_limit, "open document limit reached"); + } + if (!language_id_fits || text.size() > limits_.max_document_bytes) { + return failure(Kind::resource_limit, "open document exceeds the byte limit"); + } + if (!Void::Unicode::validate_utf8(text)) { + return failure(Kind::invalid_utf8, "document text is not valid UTF-8"); + } + return make_snapshot(*identity, language_id, client_version, std::move(text)); + }; + + if (identity->is_file_uri) { + ++overlay_epoch_; + } + auto snapshot = admit(); + if (!snapshot && by_uri_.size() - admitted_documents_ >= limits_.max_unavailable_documents) { + // The parsed scheme determines which authority an unrecorded open can affect. + if (identity->is_file_uri) { + unknown_file_open_ = true; + } else { + unknown_virtual_open_ = true; + } + return failure(Kind::resource_limit, "unavailable-open limit reached"); + } + + auto key = identity->canonical_uri; + auto [entry, inserted] = by_uri_.try_emplace( + std::move(key), + OpenDocument{ + .identity = std::move(*identity), + .language_id = + language_id_fits ? std::optional{language_id} : std::nullopt, + .highest_version = client_version, + .current = snapshot.value_or(nullptr), + .admitted = snapshot.has_value(), + .problem = snapshot ? std::string{} : snapshot.error().message, + }); + const auto &bound = entry->second.identity; + if (bound.is_file_uri && !bound.canonical_path.empty()) { + try { + by_path_.emplace(bound.canonical_path, &entry->second); + } catch (...) { + by_uri_.erase(entry); + unknown_file_open_ = true; + throw; + } + } else if (bound.is_file_uri) { + ++unbound_file_documents_; + } + admitted_documents_ += static_cast(snapshot.has_value()); + return snapshot; +} + +DocumentStore::SnapshotResult DocumentStore::apply_changes(std::string_view raw_uri, + std::int64_t new_version, + std::span edits) { + const auto key = client_uri_key(raw_uri); + if (!key) { + return failure(Kind::invalid_uri, key.error()); + } + std::unique_lock lock{mutex_}; + const auto found = by_uri_.find(*key); + if (found == by_uri_.end()) { + return failure(Kind::not_open, "document is not open"); + } + auto &document = found->second; + auto reject = [&](Kind kind, std::string reason) -> SnapshotResult { + DocumentError cause{kind, std::move(reason)}; + desynchronize(document, cause); + return std::unexpected{std::move(cause)}; + }; + + if (!std::in_range(new_version)) { + return reject(Kind::invalid_version, "change version exceeds the LSP integer range"); + } + const auto client_version = static_cast(new_version); + if (client_version <= document.highest_version) { + return reject(Kind::nonmonotonic_version, + "change notification has nonmonotonic document version"); + } + document.highest_version = client_version; + if (!document.current && (edits.empty() || edits.front().range)) { + return reject(Kind::desynchronized, + "document is desynchronized; a newer full-text replacement is required"); + } + if (!document.language_id) { + return reject(Kind::resource_limit, "document language identifier exceeds the byte limit"); + } + if (!document.admitted && admitted_documents_ >= limits_.max_open_documents) { + return reject(Kind::resource_limit, "open document limit reached"); + } + if (edits.size() > limits_.max_changes) { + return reject(Kind::resource_limit, "change notification exceeds the edit count limit"); + } + std::size_t remaining_batch_bytes = limits_.max_change_bytes; + for (const auto &edit : edits) { + if (edit.text.size() > remaining_batch_bytes || + edit.text.size() > limits_.max_document_bytes) { + return reject(Kind::resource_limit, "change notification exceeds the text byte limit"); + } + remaining_batch_bytes -= edit.text.size(); + if (!Void::Unicode::validate_utf8(edit.text)) { + return reject(Kind::invalid_utf8, "change edit text is not valid UTF-8"); + } + } + + const auto overhead = snapshot_overhead(document.identity, *document.language_id); + const auto available = available_snapshot_bytes(); + if (overhead > available) { + return reject(Kind::resource_limit, "document snapshot memory limit reached"); + } + const auto body_budget = available - overhead; + std::string working_text; + std::optional working_index; + const auto *current = document.current.get(); + std::string_view source = current ? std::string_view{current->text} : std::string_view{}; + const LineIndex *source_index = current ? ¤t->line_index : nullptr; + + for (const auto &edit : edits) { + if (!edit.range) { + source = edit.text; + source_index = nullptr; + working_index.reset(); + continue; + } + if (!working_index) { + const auto lines = + source_index ? source_index->line_count() : LineIndex::count_lines(source); + if (source.size() > body_budget || + lines > (body_budget - source.size()) / sizeof(std::size_t)) { + return reject(Kind::resource_limit, + "edit working copy exceeds the snapshot budget"); + } + working_text = std::string{source}; + working_index = source_index ? *source_index : LineIndex{source, lines}; + } + const auto offsets = working_index->range_to_offsets(working_text, *edit.range, encoding_); + if (!offsets) { + return reject(Kind::invalid_range, + "invalid incremental edit range: " + offsets.error()); + } + const auto [start, end] = *offsets; + const auto unchanged = working_text.size() - (end - start); + if (edit.text.size() > limits_.max_document_bytes - unchanged) { + return reject(Kind::resource_limit, "edited document exceeds the byte limit"); + } + const auto next_size = unchanged + edit.text.size(); + const auto text_bytes = std::max(next_size, working_text.capacity()); + if (text_bytes > body_budget || + !working_index->apply_replacement(working_text, start, end, edit.text, + (body_budget - text_bytes) / sizeof(std::size_t))) { + return reject(Kind::resource_limit, "edit working copy exceeds the snapshot budget"); + } + working_text.replace(start, end - start, edit.text); + } + + if (!working_index) { + if (source.size() > body_budget) { + return reject(Kind::resource_limit, "document snapshot memory limit reached"); + } + working_text = std::string{source}; + } + auto updated = make_snapshot(document.identity, *document.language_id, client_version, + std::move(working_text), std::move(working_index)); + if (!updated) { + desynchronize(document, updated.error()); + return updated; + } + if (!document.admitted) { + document.admitted = true; + ++admitted_documents_; + } + document.current = *updated; + document.problem.clear(); + return updated; +} + +std::expected DocumentStore::mark_desynchronized( + std::string_view raw_uri, std::optional observed_version, DocumentError cause) { + const auto key = client_uri_key(raw_uri); + if (!key) { + return failure(Kind::invalid_uri, key.error()); + } + std::unique_lock lock{mutex_}; + const auto found = by_uri_.find(*key); + if (found == by_uri_.end()) { + return failure(Kind::not_open, "document is not open"); + } + auto &document = found->second; + if (observed_version && std::in_range(*observed_version)) { + document.highest_version = + std::max(document.highest_version, static_cast(*observed_version)); + } + desynchronize(document, cause); + return {}; +} + +std::expected DocumentStore::close(std::string_view raw_uri) { + const auto key = client_uri_key(raw_uri); + if (!key) { + return failure(Kind::invalid_uri, key.error()); + } + std::unique_lock lock{mutex_}; + const auto entry = by_uri_.find(*key); + if (entry == by_uri_.end()) { + return failure(Kind::not_open, "document is not open"); + } + const auto &document = entry->second; + if (document.identity.is_file_uri) { + ++overlay_epoch_; + const auto &path = document.identity.canonical_path; + if (path.empty()) { + --unbound_file_documents_; + } else { + const auto [first, last] = by_path_.equal_range(path); + const auto bound = std::find_if( + first, last, [&](const auto &pair) { return pair.second == &document; }); + if (bound != last) { + by_path_.erase(bound); + } + } + } + admitted_documents_ -= static_cast(document.admitted); + by_uri_.erase(entry); + return {}; +} + +DocumentStore::Snapshot DocumentStore::snapshot(std::string_view raw_uri) const { + const auto key = client_uri_key(raw_uri); + if (!key) { + return {}; + } + std::shared_lock lock{mutex_}; + const auto found = by_uri_.find(*key); + return found == by_uri_.end() ? nullptr : found->second.current; +} + +DocumentStore::SnapshotResult +DocumentStore::overlay_for_path(const DocumentIdentity &identity) const { + if (unknown_file_open_ || unbound_file_documents_ != 0) { + return failure(Kind::unavailable_overlay, "one or more file opens have no known binding"); + } + const auto lexical = by_uri_.find(identity.canonical_uri); + if (lexical != by_uri_.end() && + lexical->second.identity.canonical_path != identity.canonical_path) { + return failure(Kind::stale_read, "file path changed while its client URI is open"); + } + const auto [first, last] = by_path_.equal_range(identity.canonical_path); + if (first == last) { + return Snapshot{}; + } + if (std::next(first) != last) { + return failure(Kind::ambiguous_overlay, "multiple open client URIs refer to this file"); + } + const auto &document = *first->second; + if (!document.current) { + const auto kind = document.admitted ? Kind::desynchronized : Kind::unavailable_overlay; + const auto reason = document.problem.empty() ? "waiting for full text" : document.problem; + return failure(kind, "open overlay is unavailable: " + reason); + } + return document.current; +} + +DocumentStore::Snapshot DocumentStore::snapshot_by_path(const std::filesystem::path &path) const { + const auto identity = identity_from_path(path); + if (!identity) { + return {}; + } + std::shared_lock lock{mutex_}; + return overlay_for_path(*identity).value_or(nullptr); +} + +std::vector DocumentStore::list_overlays() const { + std::shared_lock lock{mutex_}; + std::vector result; + result.reserve(admitted_documents_); + for (const auto &[uri, document] : by_uri_) { + if (document.current) { + result.push_back(document.current); + } + } + return result; +} + +std::expected +DocumentStore::file_overlay_inventory(std::size_t max_entries) const { + std::shared_lock lock{mutex_}; + if (unknown_file_open_ || unbound_file_documents_ != 0) { + return failure(Kind::unavailable_overlay, "one or more file opens have no known binding"); + } + if (by_path_.size() > max_entries) { + return failure(Kind::resource_limit, "file overlay inventory exceeds the entry limit"); + } + FileOverlayInventory inventory; + inventory.generation_ = {snapshot_bytes_, overlay_epoch_}; + inventory.entries_.reserve(by_path_.size()); + for (const auto &[path, document] : by_path_) { + inventory.entries_.push_back({document->identity, overlay_for_path(document->identity)}); + } + return inventory; +} + +bool DocumentStore::current_generation(const FileOverlayGeneration &generation) const { + return generation.store == snapshot_bytes_ && generation.epoch == overlay_epoch_; +} + +std::expected +DocumentStore::observe_bound_source(const FileOverlayInventory &inventory, + std::string_view file_uri, + const std::filesystem::path &physical_path) const { + auto identity = bound_file_identity(file_uri, physical_path); + if (!identity) { + return std::unexpected{std::move(identity.error())}; + } + + std::shared_lock lock{mutex_}; + if (!current_generation(inventory.generation_)) { + return failure(Kind::stale_read, + "file overlay inventory belongs to another store or generation"); + } + auto overlay = overlay_for_path(*identity); + if (!overlay) { + return std::unexpected{std::move(overlay.error())}; + } + BoundSourceObservation observation; + observation.generation_ = inventory.generation_; + observation.identity_ = std::move(*identity); + observation.overlay_ = std::move(*overlay); + return observation; +} + +std::expected +DocumentStore::check_observation(const BoundSourceObservation &observation) const { + if (!current_generation(observation.generation_)) { + return failure(Kind::stale_read, "bound source belongs to another store or generation"); + } + auto current = overlay_for_path(observation.identity_); + if (!current) { + return std::unexpected{std::move(current.error())}; + } + if (*current != observation.overlay_) { + return failure(Kind::stale_read, "selected overlay changed after observation"); + } + return {}; +} + +DocumentStore::SnapshotResult +DocumentStore::materialize_bound_disk(const BoundSourceObservation &observation, + std::string bytes) const { + std::unique_lock lock{mutex_}; + if (auto valid = check_observation(observation); !valid) { + return std::unexpected{std::move(valid.error())}; + } + if (observation.overlay_) { + return failure(Kind::already_open, "an open overlay supplies the bound source"); + } + if (bytes.size() > limits_.max_document_bytes) { + return failure(Kind::resource_limit, "bound disk document exceeds the byte limit"); + } + if (!Void::Unicode::validate_utf8(bytes)) { + return failure(Kind::invalid_utf8, "bound disk document is not valid UTF-8"); + } + return make_snapshot(observation.identity_, "cpp", std::nullopt, std::move(bytes)); +} + +std::expected +DocumentStore::validate_bound_sources(const FileOverlayInventory &inventory, + std::span selected) const { + return validate_bound_sources(inventory.generation(), selected); +} + +std::expected +DocumentStore::validate_bound_sources(const FileOverlayGeneration &generation, + std::span selected) const { + std::shared_lock lock{mutex_}; + if (!current_generation(generation)) { + return failure(Kind::stale_read, + "file overlay inventory belongs to another store or generation"); + } + for (const auto &observation : selected) { + if (auto valid = check_observation(observation); !valid) { + return valid; + } + } + return {}; +} + +DocumentStore::SnapshotResult DocumentStore::resolve_content(const std::filesystem::path &path, + std::size_t max_bytes) const { + auto identity = identity_from_path(path); + if (!identity) { + return failure(Kind::invalid_uri, std::move(identity.error())); + } + + std::uint64_t epoch; + { + std::shared_lock lock{mutex_}; + auto overlay = overlay_for_path(*identity); + if (!overlay || *overlay) { + return overlay; + } + epoch = overlay_epoch_; + } + + auto disk = identity->canonical_path.empty() + ? failure(Kind::disk_read_failed, "cannot resolve physical disk path") + : read_regular_file(identity->canonical_path, + std::min(max_bytes, limits_.max_document_bytes)); + if (disk && !Void::Unicode::validate_utf8(disk->text)) { + disk = failure(Kind::invalid_utf8, "disk document is not valid UTF-8"); + } + if (after_disk_read_) { + after_disk_read_(); + } + auto latest = identity_from_path(path); +#ifndef _WIN32 + if (disk && latest) { + struct stat current{}; + if (::stat(latest->canonical_path.c_str(), ¤t) != 0 || + !Detail::same_file_state(disk->file.metadata, current)) + disk = failure(Kind::stale_read, "disk document changed before publication"); + } +#endif + std::unique_lock lock{mutex_}; + if (!latest) { + return failure(Kind::stale_read, "disk path could not be revalidated"); + } + auto overlay = overlay_for_path(*latest); + if (!overlay || *overlay) { + return overlay; + } + if (epoch != overlay_epoch_ || latest->canonical_path != identity->canonical_path || + latest->canonical_uri != identity->canonical_uri) { + return failure(Kind::stale_read, "document binding or encoding changed during disk read"); + } + if (!disk) { + return std::unexpected{std::move(disk.error())}; + } + return make_snapshot(*latest, "cpp", std::nullopt, std::move(disk->text)); +} + +} // namespace Void::LanguageServer::Documents diff --git a/src/Documents/Position.cpp b/src/Documents/Position.cpp new file mode 100644 index 0000000..e99da43 --- /dev/null +++ b/src/Documents/Position.cpp @@ -0,0 +1,299 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Documents { +namespace { + +Void::Unicode::detail::Utf8Step step_utf8(std::string_view text, std::size_t offset) noexcept { + const std::size_t avail = std::min(4, text.size() - offset); + std::array bytes{}; + for (std::size_t i = 0; i < avail; ++i) { + bytes[i] = static_cast(text[offset + i]); + } + return Void::Unicode::detail::inspect_utf8(std::span{bytes.data(), avail}); +} + +std::size_t ascii_prefix_size(std::string_view text) noexcept { + constexpr std::uint64_t high_bits = 0x8080808080808080ULL; + const auto *bytes = text.data(); + const auto size = text.size(); + std::size_t offset = 0; + // Check full words first. memcpy supports unaligned input, and the mask works in either byte + // order. + for (; size - offset >= sizeof(high_bits); offset += sizeof(high_bits)) { + std::uint64_t word; + std::memcpy(&word, bytes + offset, sizeof(word)); + if ((word & high_bits) != 0) { + break; + } + } + while (offset < size && static_cast(bytes[offset]) < 0x80) { + ++offset; + } + return offset; +} + +struct LineCursor { + std::size_t bytes{}; + std::size_t utf16_units{}; + + [[nodiscard]] std::size_t units(PositionEncoding encoding) const noexcept { + return encoding == PositionEncoding::utf8 ? bytes : utf16_units; + } + + [[nodiscard]] std::expected seek(std::string_view line, std::size_t target, + PositionEncoding encoding, + const char *split_error) { + while (bytes < line.size() && units(encoding) < target) { + const auto room = target - units(encoding); + const auto ascii = + ascii_prefix_size(line.substr(bytes, std::min(room, line.size() - bytes))); + bytes += ascii; + utf16_units += ascii; + if (ascii == room || bytes == line.size()) { + break; + } + + const auto step = step_utf8(line, bytes); + if (step.status != Void::Unicode::detail::StepStatus::ok) { + return std::unexpected{"invalid UTF-8 encountered on line"}; + } + const auto count = Void::Unicode::detail::utf16_length(step.scalar.code_point()); + if ((encoding == PositionEncoding::utf8 ? step.consumed : count) > room - ascii) { + return std::unexpected{split_error}; + } + bytes += step.consumed; + utf16_units += count; + } + return {}; + } +}; + +std::expected, std::string> +offsets_on_line(const LineIndex &index, std::string_view text, Position first, + std::uint32_t last_character, PositionEncoding encoding) { + if (first.line > kMaxPositionValue || first.character > kMaxPositionValue) { + return std::unexpected{"position exceeds the LSP integer range"}; + } + const auto line_start = index.line_start_offset(first.line); + if (!line_start) { + return std::unexpected{"position line out of range"}; + } + const auto line_end = index.line_content_end_offset(text, first.line); + if (!line_end) { + return std::unexpected{"line index does not match text"}; + } + + const auto line = text.substr(*line_start, *line_end - *line_start); + const auto *split_error = encoding == PositionEncoding::utf8 + ? "UTF-8 character offset splits a Unicode scalar" + : "UTF-16 character offset splits a surrogate pair"; + LineCursor cursor; + if (auto result = cursor.seek(line, first.character, encoding, split_error); !result) { + return std::unexpected{std::move(result.error())}; + } + const auto start_offset = *line_start + cursor.bytes; + if (last_character == first.character) { + return std::pair{start_offset, start_offset}; + } + if (last_character > kMaxPositionValue) { + return std::unexpected{"position exceeds the LSP integer range"}; + } + if (auto result = cursor.seek(line, last_character, encoding, split_error); !result) { + return std::unexpected{std::move(result.error())}; + } + return std::pair{start_offset, *line_start + cursor.bytes}; +} + +bool ends_line(char byte, char next) noexcept { + return byte == '\n' || (byte == '\r' && next != '\n'); +} + +template void visit_line_starts(std::string_view text, char next, Add add) { + for (std::size_t i = 0; i < text.size(); ++i) { + if (ends_line(text[i], i + 1 < text.size() ? text[i + 1] : next)) { + add(i + 1); + } + } +} + +} // namespace + +LineIndex::LineIndex(std::string_view text) : LineIndex(text, count_lines(text)) {} + +LineIndex::LineIndex(std::string_view text, std::size_t line_count) : text_size_{text.size()} { + line_starts_.reserve(line_count); + visit_line_starts(text, '\0', [&](std::size_t start) { line_starts_.push_back(start); }); +} + +std::size_t LineIndex::count_lines(std::string_view text) noexcept { + std::size_t count = 1; + for (std::size_t i = 0; i < text.size(); ++i) { + if (ends_line(text[i], i + 1 < text.size() ? text[i + 1] : '\0')) { + ++count; + } + } + return count; +} + +std::size_t LineIndex::storage_bytes() const noexcept { + return line_starts_.capacity() * sizeof(std::size_t); +} + +bool LineIndex::apply_replacement(std::string_view text, std::size_t start, std::size_t end, + std::string_view replacement, std::size_t max_lines) { + // A line start at either edge can change when the splice forms or breaks a CRLF. + // Starts strictly after the right edge only need an offset adjustment. + const auto first = std::lower_bound(line_starts_.begin() + 1, line_starts_.end(), start); + const auto last = std::upper_bound(first, line_starts_.end(), end); + const auto first_index = static_cast(first - line_starts_.begin()); + const auto removed = static_cast(last - first); + const char following = end < text.size() ? text[end] : '\0'; + const char first_byte = replacement.empty() ? following : replacement.front(); + const bool start_is_boundary = start > 0 && ends_line(text[start - 1], first_byte); + std::size_t inserted = start_is_boundary ? 1 : 0; + visit_line_starts(replacement, following, [&](std::size_t) { ++inserted; }); + const auto new_count = line_starts_.size() - removed + inserted; + if (std::max(new_count, line_starts_.capacity()) > max_lines) { + return false; + } + + if (removed > inserted) { + line_starts_.erase(first + inserted, last); + } else if (inserted > removed) { + // The insertion uses saved indices since reserve can invalidate both iterators. + line_starts_.reserve(new_count); + line_starts_.insert(line_starts_.begin() + first_index + removed, inserted - removed, 0); + } + auto output = line_starts_.begin() + first_index; + if (start_is_boundary) { + *output++ = start; + } + visit_line_starts(replacement, following, + [&](std::size_t offset) { *output++ = start + offset; }); + const auto bytes_removed = end - start; + text_size_ = text.size() - bytes_removed + replacement.size(); + if (bytes_removed != replacement.size()) { + for (; output != line_starts_.end(); ++output) { + *output = *output - bytes_removed + replacement.size(); + } + } + return true; +} + +std::optional LineIndex::line_start_offset(std::uint32_t line) const noexcept { + if (line >= line_starts_.size()) { + return std::nullopt; + } + return line_starts_[line]; +} + +std::optional LineIndex::line_content_end_offset(std::string_view text, + std::uint32_t line) const noexcept { + const auto start = line_start_offset(line); + if (!start || text.size() != text_size_) { + return std::nullopt; + } + const auto next_line = static_cast(line) + 1; + const std::size_t raw_end = + next_line < line_starts_.size() ? line_starts_[next_line] : text.size(); + if (*start > raw_end || raw_end > text.size()) { + return std::nullopt; + } + std::size_t end = raw_end; + if (end > *start && text[end - 1] == '\n') { + --end; + if (end > *start && text[end - 1] == '\r') { + --end; + } + } else if (end > *start && text[end - 1] == '\r') { + --end; + } + return end; +} + +std::expected +LineIndex::position_to_offset(std::string_view text, Position position, + PositionEncoding encoding) const { + auto offsets = offsets_on_line(*this, text, position, position.character, encoding); + if (!offsets) { + return std::unexpected{std::move(offsets.error())}; + } + return offsets->first; +} + +std::expected +LineIndex::offset_to_position(std::string_view text, std::size_t byte_offset, + PositionEncoding encoding) const { + if (byte_offset > text.size()) { + return std::unexpected{"byte offset out of range"}; + } + // Reject landing between '\r' and '\n' of a CRLF sequence. + if (byte_offset > 0 && byte_offset < text.size() && text[byte_offset - 1] == '\r' && + text[byte_offset] == '\n') { + return std::unexpected{"byte offset splits a CRLF line terminator"}; + } + + const auto it = std::upper_bound(line_starts_.begin(), line_starts_.end(), byte_offset); + if (it == line_starts_.begin()) { + return std::unexpected{"line index does not match text"}; + } + const auto line_idx = static_cast(it - line_starts_.begin() - 1); + if (line_idx > kMaxPositionValue) { + return std::unexpected{"position exceeds the LSP integer range"}; + } + const std::size_t line_start = line_starts_[line_idx]; + const auto line_end = line_content_end_offset(text, static_cast(line_idx)); + if (!line_end) { + return std::unexpected{"line index does not match text"}; + } + if (byte_offset > *line_end) { + return std::unexpected{"byte offset lands inside line terminator"}; + } + + const auto line_view = text.substr(line_start, *line_end - line_start); + LineCursor cursor; + if (auto result = cursor.seek(line_view, byte_offset - line_start, PositionEncoding::utf8, + "byte offset splits a Unicode scalar"); + !result) { + return std::unexpected{std::move(result.error())}; + } + const auto units = cursor.units(encoding); + if (units > kMaxPositionValue) { + return std::unexpected{"position exceeds the LSP integer range"}; + } + + return Position{ + .line = static_cast(line_idx), + .character = static_cast(units), + }; +} + +std::expected, std::string> +LineIndex::range_to_offsets(std::string_view text, Range range, PositionEncoding encoding) const { + if (range.end < range.start) { + return std::unexpected{"range end precedes range start"}; + } + if (range.start.line == range.end.line) { + return offsets_on_line(*this, text, range.start, range.end.character, encoding); + } + auto start = position_to_offset(text, range.start, encoding); + if (!start) { + return std::unexpected{std::move(start.error())}; + } + auto end = position_to_offset(text, range.end, encoding); + if (!end) { + return std::unexpected{std::move(end.error())}; + } + return std::pair{*start, *end}; +} + +} // namespace Void::LanguageServer::Documents diff --git a/src/Documents/Uri.cpp b/src/Documents/Uri.cpp new file mode 100644 index 0000000..13de4ae --- /dev/null +++ b/src/Documents/Uri.cpp @@ -0,0 +1,237 @@ +#include + +#include +#include + +#include +#include + +namespace Void::LanguageServer::Documents { +namespace { + +bool is_ascii_letter(char ch) noexcept { + return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); +} + +bool is_scheme_char(char ch) noexcept { + return is_ascii_letter(ch) || (ch >= '0' && ch <= '9') || ch == '+' || ch == '-' || ch == '.'; +} + +std::string to_lower_ascii(std::string_view text) { + std::string out{text}; + for (char &ch : out) { + if (ch >= 'A' && ch <= 'Z') { + ch = static_cast(ch + ('a' - 'A')); + } + } + return out; +} + +std::string_view utf8_bytes(const std::u8string &text) noexcept { + return {reinterpret_cast(text.data()), text.size()}; +} + +std::filesystem::path physical_path(const std::filesystem::path &absolute_path) { + namespace fs = std::filesystem; + std::error_code error; + auto resolved = fs::canonical(absolute_path, error); + if (!error) + return resolved; + if (error != std::errc::no_such_file_or_directory) + return {}; + + // Unsaved, newly created files may have an ordinary missing suffix. + // A missing component followed by '..' cannot be traversed on disk. + fs::path prefix = absolute_path.root_path(); + bool missing = false; + for (const auto &part : absolute_path.relative_path()) { + if (!missing) { + prefix /= part; + const auto status = fs::symlink_status(prefix, error); + if (error && error != std::errc::no_such_file_or_directory) + return {}; + if (status.type() != fs::file_type::not_found) + continue; + resolved = fs::canonical(prefix.parent_path(), error); + if (error || !fs::is_directory(resolved, error) || error) + return {}; + missing = true; + } + if (part.empty() || part == "..") + return {}; + if (part != ".") + resolved /= part; + } + return missing ? resolved : fs::path{}; +} + +struct ParsedUri { + std::string key; + std::filesystem::path path; +}; + +std::expected parse_client_uri(std::string_view uri) { + if (uri.size() > kMaxDocumentUriBytes) { + return std::unexpected{"document URI exceeds the byte limit"}; + } + if (!Void::Unicode::validate_utf8(uri)) { + return std::unexpected{"document URI must be valid UTF-8"}; + } + for (const unsigned char ch : uri) { + if (ch <= 0x20 || ch == 0x7f || + std::string_view{"<>\"{}|\\^`"}.find(ch) != std::string_view::npos) { + return std::unexpected{"document URI contains a character that must be escaped"}; + } + } + + const auto colon = uri.find(':'); + if (colon == std::string_view::npos || colon == 0) { + return std::unexpected{"document URI missing scheme"}; + } + auto raw_scheme = uri.substr(0, colon); + if (!is_ascii_letter(raw_scheme.front())) { + return std::unexpected{"document URI has invalid scheme"}; + } + for (char ch : raw_scheme.substr(1)) { + if (!is_scheme_char(ch)) { + return std::unexpected{"document URI has invalid scheme"}; + } + } + auto scheme = to_lower_ascii(raw_scheme); + auto rest = uri.substr(colon + 1); + if (rest.empty()) { + return std::unexpected{"document URI missing scheme-specific content"}; + } + + const bool is_file = scheme == "file"; + for (auto offset = rest.find('%'); offset != std::string_view::npos; + offset = rest.find('%', offset + 3)) { + if (rest.size() - offset < 3) { + return std::unexpected{"document URI contains malformed percent encoding"}; + } + const auto decoded = Void::Encoding::Url::decode(rest.substr(offset, 3)); + if (!decoded) { + return std::unexpected{"document URI contains malformed percent encoding"}; + } + const char byte = decoded->front(); + if (byte == '\0' || (is_file && (byte == '/' || byte == '\\'))) { + return std::unexpected{"document URI contains an encoded separator or NUL"}; + } + } + if (!is_file) { + // Virtual schemes own the spelling and meaning of their scheme-specific part. + return ParsedUri{std::move(scheme) + ":" + std::string{rest}, {}}; + } + + if (rest.starts_with("//")) { + rest.remove_prefix(2); + const auto slash = rest.find('/'); + if (slash == std::string_view::npos) { + return std::unexpected{"file URI missing absolute path"}; + } + auto authority = rest.substr(0, slash); + if (!authority.empty() && to_lower_ascii(authority) != "localhost") { + return std::unexpected{"remote file URI authority is unsupported"}; + } + rest.remove_prefix(slash); + } + if (!rest.starts_with('/') || rest.starts_with("//")) { + return std::unexpected{"file URI requires a local absolute path"}; + } + if (rest.find_first_of("?#") != std::string_view::npos) { + return std::unexpected{"file URI must not contain a query or fragment"}; + } + + auto decoded = Void::Encoding::Url::decode(rest); + if (!decoded || !Void::Unicode::validate_utf8(*decoded)) { + return std::unexpected{"decoded file URI path is not valid UTF-8"}; + } +#ifdef _WIN32 + // Local drive paths in a file URI have a leading slash before the drive letter. + if (decoded->size() < 4 || !is_ascii_letter((*decoded)[1]) || decoded->substr(2, 2) != ":/") { + return std::unexpected{"file URI requires a local absolute drive path"}; + } + decoded->erase(0, 1); +#endif + std::filesystem::path path{std::u8string{decoded->begin(), decoded->end()}}; + return ParsedUri{path_to_file_uri(path), std::move(path)}; +} + +} // namespace + +std::string path_to_file_uri(const std::filesystem::path &absolute_path) { + const auto generic_utf8 = absolute_path.generic_u8string(); + auto path = utf8_bytes(generic_utf8); + std::string encoded = "file://"; + if (!path.starts_with('/')) { + encoded.push_back('/'); + } +#ifdef _WIN32 + if (path.size() >= 3 && is_ascii_letter(path.front()) && path.substr(1, 2) == ":/") { + encoded.append(path.substr(0, 2)); + path.remove_prefix(2); + } +#endif + const auto slash = '/'; + while (!path.empty()) { + const auto next = path.find(slash); + encoded += Void::Encoding::Url::encode(path.substr(0, next)); + if (next == std::string_view::npos) { + break; + } + encoded.push_back(slash); + path.remove_prefix(next + 1); + } + return encoded; +} + +std::expected client_uri_key(std::string_view raw_uri) { + return parse_client_uri(raw_uri).transform([](ParsedUri uri) { return std::move(uri.key); }); +} + +std::expected client_file_path(std::string_view raw_uri) { + return parse_client_uri(raw_uri).transform([](ParsedUri uri) { return std::move(uri.path); }); +} + +std::expected normalize_uri(std::string_view raw_uri) { + auto uri = parse_client_uri(raw_uri); + if (!uri) { + return std::unexpected{std::move(uri.error())}; + } + const bool is_file = !uri->path.empty(); + return DocumentIdentity{ + .canonical_uri = std::move(uri->key), + .display_uri = std::string{raw_uri}, + .canonical_path = is_file ? physical_path(uri->path) : std::filesystem::path{}, + .is_file_uri = is_file, + }; +} + +std::expected identity_from_path(const std::filesystem::path &path) { + if (path.empty() || path.native().find(std::filesystem::path::value_type{}) != + std::filesystem::path::string_type::npos) { + return std::unexpected{"filesystem path is empty or contains NUL"}; + } + std::error_code error; + auto absolute_path = std::filesystem::absolute(path, error); + if (error) { + return std::unexpected{"cannot make filesystem path absolute"}; + } + const auto generic_utf8 = absolute_path.generic_u8string(); + const auto absolute_text = utf8_bytes(generic_utf8); + if (absolute_text.size() > kMaxDocumentUriBytes || + absolute_text.find('\\') != std::string_view::npos || + !Void::Unicode::validate_utf8(absolute_text)) { + return std::unexpected{"filesystem path cannot be represented as a local document URI"}; + } + // Keep the spelling of segments like '..' until physical resolution, where symlinks matter. + const auto uri = path_to_file_uri(absolute_path); + return DocumentIdentity{ + .canonical_uri = uri, + .display_uri = uri, + .canonical_path = physical_path(absolute_path), + .is_file_uri = true, + }; +} + +} // namespace Void::LanguageServer::Documents diff --git a/src/Json.cpp b/src/Json.cpp deleted file mode 100644 index bc5ee7c..0000000 --- a/src/Json.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include - -#include - -#include -#include -#include -#include - -namespace vls { - -std::expected parse_json(std::string_view text, std::size_t maximum_depth) { - if (!Void::Unicode::validate_utf8(text)) - return std::unexpected{"invalid UTF-8"}; - - // Bound structural nesting before calling a recursive dependency parser. - // This scan does not parse JSON or numbers: StrictJson owns that grammar, - // including escape validation and rejection of unpaired surrogate escapes. - std::size_t depth{}; - bool in_string = false; - bool escaped = false; - for (const char c : text) { - if (in_string) { - if (escaped) - escaped = false; - else if (c == '\\') - escaped = true; - else if (c == '"') - in_string = false; - } else if (c == '"') { - in_string = true; - } else if (c == '{' || c == '[') { - if (depth >= maximum_depth) - return std::unexpected{"JSON nesting exceeds depth limit"}; - ++depth; - } else if ((c == '}' || c == ']') && depth > 0) { - --depth; - } - } - auto parsed = Void::Json::Strict::parse(text, maximum_depth); - if (!parsed) - return std::unexpected{parsed.error().message}; - return std::move(*parsed); -} - -std::expected request_id(const Json &value) { - // LSP integer IDs are constrained by value, not by JSON number spelling. - // Preserve the value only after checking integrality and the signed range. - return std::visit( - [](const auto &item) -> std::expected { - using T = std::remove_cvref_t; - if constexpr (std::is_same_v) { - return RequestId{item}; - } else if constexpr (std::is_integral_v && !std::is_same_v) { - if (std::in_range(item)) - return RequestId{static_cast(item)}; - } else if constexpr (std::is_floating_point_v) { - const long double wide = static_cast(item); - if (std::isfinite(item) && std::trunc(item) == item && - wide >= std::numeric_limits::min() && - wide <= std::numeric_limits::max()) - return RequestId{static_cast(item)}; - } - return std::unexpected{"request ID must be a signed 32-bit integer or string"}; - }, - value.value); -} - -std::string quote_json(std::string_view text) { - constexpr char hex[] = "0123456789abcdef"; - std::string result{"\""}; - for (const unsigned char c : text) { - if (c == '"' || c == '\\') { - result.push_back('\\'); - result.push_back(static_cast(c)); - } else if (c < 0x20) { - result += "\\u00"; - result.push_back(hex[c >> 4]); - result.push_back(hex[c & 15]); - } else { - result.push_back(static_cast(c)); - } - } - result.push_back('"'); - return result; -} - -std::string encode_id(const RequestId &id) { - return std::visit( - [](const auto &item) -> std::string { - if constexpr (std::is_same_v, std::string>) - return quote_json(item); - else - return std::to_string(item); - }, - id); -} - -} // namespace vls diff --git a/src/Framing.cpp b/src/Protocol/Framing.cpp similarity index 61% rename from src/Framing.cpp rename to src/Protocol/Framing.cpp index 428359d..58f5721 100644 --- a/src/Framing.cpp +++ b/src/Protocol/Framing.cpp @@ -1,51 +1,60 @@ -#include +#include #include #include #include #include +#include -namespace vls { +namespace Void::LanguageServer::Protocol { namespace { std::string_view trim(std::string_view text) { const auto first = text.find_first_not_of(" \t"); - if (first == std::string_view::npos) + if (first == std::string_view::npos) { return {}; + } return text.substr(first, text.find_last_not_of(" \t") - first + 1); } -std::string lower(std::string_view text) { +std::string to_ascii_lower(std::string_view text) { std::string result{text}; - for (char &c : result) - if (c >= 'A' && c <= 'Z') - c = static_cast(c + ('a' - 'A')); + for (char &ch : result) { + if (ch >= 'A' && ch <= 'Z') { + ch = static_cast(ch + ('a' - 'A')); + } + } return result; } -bool supported_content_type(std::string_view text) { +bool is_supported_content_type(std::string_view text) { auto separator = text.find(';'); - const auto media = lower(trim(text.substr(0, separator))); - if (media != "application/vscode-jsonrpc" && media != "application/json") + const auto media = to_ascii_lower(trim(text.substr(0, separator))); + if (media != "application/vscode-jsonrpc" && media != "application/json") { return false; + } bool seen_charset = false; while (separator != std::string_view::npos) { text.remove_prefix(separator + 1); separator = text.find(';'); const auto parameter = trim(text.substr(0, separator)); const auto equals = parameter.find('='); - if (equals == std::string_view::npos) + if (equals == std::string_view::npos) { return false; - if (lower(trim(parameter.substr(0, equals))) == "charset") { - if (seen_charset) + } + if (to_ascii_lower(trim(parameter.substr(0, equals))) == "charset") { + if (seen_charset) { return false; + } seen_charset = true; auto encoding = trim(parameter.substr(equals + 1)); - if (encoding.size() >= 2 && encoding.front() == '"' && encoding.back() == '"') + if (encoding.size() >= 2 && encoding.front() == '"' && encoding.back() == '"') { encoding = encoding.substr(1, encoding.size() - 2); - const auto name = lower(encoding); - if (name != "utf-8" && name != "utf8") + } + const auto name = to_ascii_lower(encoding); + if (name != "utf-8" && name != "utf8") { return false; + } } } return true; @@ -59,21 +68,26 @@ std::expected, std::string> read_frame(std::istream & while (!header.ends_with("\r\n\r\n")) { const auto next = input.get(); if (next == std::char_traits::eof()) { - if (input.bad() || !input.eof()) + if (input.bad() || !input.eof()) { return std::unexpected{"input stream failure"}; - if (header.empty()) + } + if (header.empty()) { return std::optional{}; + } return std::unexpected{"truncated frame header"}; } - if (header.size() >= limits.header_bytes) + if (header.size() >= limits.header_bytes) { return std::unexpected{"frame header exceeds byte limit"}; - const char c = static_cast(next); - if ((c == '\n' && (header.empty() || header.back() != '\r')) || - (!header.empty() && header.back() == '\r' && c != '\n')) + } + const char ch = static_cast(next); + if ((ch == '\n' && (header.empty() || header.back() != '\r')) || + (!header.empty() && header.back() == '\r' && ch != '\n')) { return std::unexpected{"frame headers require CRLF"}; - if (c != '\r' && c != '\n' && c != '\t' && (c < 0x20 || c > 0x7e)) + } + if (ch != '\r' && ch != '\n' && ch != '\t' && (ch < 0x20 || ch > 0x7e)) { return std::unexpected{"non-ASCII frame header"}; - header.push_back(c); + } + header.push_back(ch); } std::optional length; @@ -83,49 +97,71 @@ std::expected, std::string> read_frame(std::istream & const auto end = remaining.find("\r\n"); const auto line = remaining.substr(0, end); const auto colon = line.find(':'); - if (colon == std::string_view::npos || colon == 0) + if (colon == std::string_view::npos || colon == 0) { return std::unexpected{"invalid frame header field"}; + } const auto name = line.substr(0, colon); - if (name.find_first_of(" \t") != std::string_view::npos) + if (name.find_first_of(" \t") != std::string_view::npos) { return std::unexpected{"invalid frame header name"}; + } const auto value = trim(line.substr(colon + 1)); - if (lower(name) == "content-length") { - if (length) + const auto lower_name = to_ascii_lower(name); + if (lower_name == "content-length") { + if (length) { return std::unexpected{"duplicate Content-Length"}; - if (value.empty() || value.find_first_not_of("0123456789") != std::string_view::npos) + } + if (value.empty() || value.find_first_not_of("0123456789") != std::string_view::npos) { return std::unexpected{"invalid Content-Length"}; + } std::size_t parsed{}; const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed); - if (result.ec != std::errc{} || result.ptr != value.data() + value.size()) + if (result.ec != std::errc{} || result.ptr != value.data() + value.size()) { return std::unexpected{"Content-Length overflow"}; - if (parsed > limits.body_bytes || parsed > std::numeric_limits::max()) + } + if (parsed > limits.body_bytes || + parsed > static_cast(std::numeric_limits::max())) { return std::unexpected{"frame body exceeds byte limit"}; + } length = parsed; - } else if (lower(name) == "content-type") { - if (seen_type || !supported_content_type(value)) + } else if (lower_name == "content-type") { + if (seen_type || !is_supported_content_type(value)) { return std::unexpected{"duplicate or unsupported Content-Type/charset"}; + } seen_type = true; } remaining.remove_prefix(end + 2); } - if (!length) + if (!length) { return std::unexpected{"missing Content-Length"}; + } std::string body(*length, '\0'); input.read(body.data(), static_cast(*length)); - if (!input) + if (!input) { return std::unexpected{"truncated frame body or input failure"}; + } return std::optional{std::move(body)}; } std::expected write_frame(std::ostream &output, std::string_view body) { - if (body.size() > static_cast(std::numeric_limits::max())) + if (body.size() > static_cast(std::numeric_limits::max())) { return std::unexpected{"output frame exceeds stream limit"}; + } output << "Content-Length: " << body.size() << "\r\n\r\n"; output.write(body.data(), static_cast(body.size())); output.flush(); - if (!output) + if (!output) { return std::unexpected{"output stream failure"}; + } return {}; } -} // namespace vls +std::expected write_json_frame(std::ostream &output, const Json &body, + std::size_t maximum_depth) { + auto encoded = serialize_json(body, maximum_depth); + if (!encoded) { + return std::unexpected{std::move(encoded.error())}; + } + return write_frame(output, *encoded); +} + +} // namespace Void::LanguageServer::Protocol diff --git a/src/Protocol/Json.cpp b/src/Protocol/Json.cpp new file mode 100644 index 0000000..d29012e --- /dev/null +++ b/src/Protocol/Json.cpp @@ -0,0 +1,160 @@ +#include + +#include + +#include +#include +#include +#include +#include + +namespace Void::LanguageServer::Protocol { +namespace { + +constexpr auto depth_error = "JSON nesting exceeds depth limit"; + +bool fits_container_depth(const Json &value, std::size_t remaining_depth) { + const auto *array = as_array(&value); + const auto *object = as_object(&value); + if (!array && !object) { + return true; + } + if (remaining_depth == 0) { + return false; + } + + const auto fits_child = [remaining_depth](const Json &child) { + return fits_container_depth(child, remaining_depth - 1); + }; + if (array) { + return std::ranges::all_of(*array, fits_child); + } + return std::ranges::all_of(*object | std::views::values, fits_child); +} + +} // namespace + +std::expected parse_json(std::string_view text, std::size_t maximum_depth) { + if (!Void::Unicode::validate_utf8(text)) { + return std::unexpected{"invalid UTF-8"}; + } + + maximum_depth = std::min(maximum_depth, kDefaultMaxJsonDepth); + // Count container openings before handing grammar and escape validation to StrictJson. + std::size_t depth{}; + bool in_string = false; + bool escaped = false; + for (const char ch : text) { + if (in_string) { + if (escaped) { + escaped = false; + } else if (ch == '\\') { + escaped = true; + } else if (ch == '"') { + in_string = false; + } + } else if (ch == '"') { + in_string = true; + } else if (ch == '{' || ch == '[') { + if (depth >= maximum_depth) { + return std::unexpected{depth_error}; + } + ++depth; + } else if ((ch == '}' || ch == ']') && depth > 0) { + --depth; + } + } + auto parsed = Void::Json::Strict::parse(text, maximum_depth); + if (!parsed) { + return std::unexpected{std::move(parsed.error().message)}; + } + return std::move(*parsed); +} + +std::expected serialize_json(const Json &value, + std::size_t maximum_depth) { + maximum_depth = std::min(maximum_depth, kDefaultMaxJsonDepth); + // StrictJson starts at depth zero, so an empty over-depth container can have no + // children to trigger its limit. Count each container before encoding. + if (!fits_container_depth(value, maximum_depth)) { + return std::unexpected{depth_error}; + } + auto encoded = Void::Json::Strict::serialize(value, maximum_depth); + if (!encoded) { + return std::unexpected{std::move(encoded.error().message)}; + } + return std::move(*encoded); +} + +std::expected request_id(const Json &value) { + if (const auto *text = as_string(&value)) { + return RequestId{*text}; + } + // StrictJson currently exposes decoded numbers. Exact wire-token validation + // requires upstream numeric metadata. + if (const auto number = as_int64(&value); number && std::in_range(*number)) { + return RequestId{static_cast(*number)}; + } + return std::unexpected{"request ID must be a signed 32-bit integer or string"}; +} + +Json request_id_json(RequestId id) { + if (const auto *number = std::get_if(&id)) { + return Json{static_cast(*number)}; + } + return Json{std::get(std::move(id))}; +} + +const Json *find_member(const Json::Object &object, std::string_view key) noexcept { + const auto found = object.find(key); + return found == object.end() ? nullptr : &found->second; +} + +const Json::Object *as_object(const Json *value) noexcept { + return value ? std::get_if(&value->value) : nullptr; +} + +const Json::Array *as_array(const Json *value) noexcept { + return value ? std::get_if(&value->value) : nullptr; +} + +const std::string *as_string(const Json *value) noexcept { + return value ? std::get_if(&value->value) : nullptr; +} + +std::optional as_bool(const Json *value) noexcept { + if (!value) { + return std::nullopt; + } + if (const auto *flag = std::get_if(&value->value)) { + return *flag; + } + return std::nullopt; +} + +std::optional as_int64(const Json *value) noexcept { + if (!value) { + return std::nullopt; + } + if (const auto *number = std::get_if(&value->value)) { + return *number; + } + // A double rounds INT64_MAX up to 2^63. Use an exclusive upper bound. + constexpr auto lower_bound = static_cast(std::numeric_limits::min()); + if (const auto *number = std::get_if(&value->value); number && *number >= lower_bound && + *number < -lower_bound && + std::trunc(*number) == *number) { + return static_cast(*number); + } + return std::nullopt; +} + +std::optional as_uint32(const Json *value) noexcept { + const auto parsed = as_int64(value); + if (!parsed || !std::in_range(*parsed)) { + return std::nullopt; + } + return static_cast(*parsed); +} + +} // namespace Void::LanguageServer::Protocol diff --git a/src/Server.cpp b/src/Server.cpp index cb45093..3711a12 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -1,51 +1,148 @@ #include +#include #include +#include +#include +#include #include +#include #include +#include +#include namespace vls { namespace { -const Json *member(const Json::Object &object, std::string_view key) { - const auto found = object.find(key); - return found == object.end() ? nullptr : &found->second; +namespace Protocol = Void::LanguageServer::Protocol; +using Protocol::as_object; +using Protocol::as_string; +using Protocol::find_member; + +const Json *member(const Json *value, std::string_view key) { + const auto *object = as_object(value); + return object ? find_member(*object, key) : nullptr; } -const std::string *string(const Json *value) { - return value ? std::get_if(&value->value) : nullptr; +// One writer serves both compiler notifications and request responses. Enqueueing a +// publication never holds the input owner's lock across a potentially blocking stream write. +class Output { + public: + Output(std::ostream &stream, bool asynchronous) : stream_(stream), asynchronous_(asynchronous) { + if (asynchronous_) + writer_ = std::jthread([this] { drain(); }); + } + ~Output() { finish(); } + bool send(std::string body) { + if (!asynchronous_) + return bool(write_frame(stream_, body)); + std::lock_guard lock{mutex_}; + constexpr std::size_t limit = 32 * 1024 * 1024; + if (finished_ || failed_ || queue_.size() >= 512 || body.size() > limit - bytes_) { + failed_ = true; + wake_.notify_one(); + return false; + } + bytes_ += body.size(); + queue_.push_back(std::move(body)); + wake_.notify_one(); + return true; + } + bool finish() { + { + std::lock_guard lock{mutex_}; + finished_ = true; + wake_.notify_one(); + } + if (writer_.joinable()) + writer_.join(); + return !failed_; + } + + private: + std::ostream &stream_; + bool asynchronous_, finished_{}, failed_{}; + std::mutex mutex_; + std::condition_variable wake_; + std::deque queue_; + std::size_t bytes_{}; + std::jthread writer_; + void drain() { + std::unique_lock lock{mutex_}; + for (;;) { + wake_.wait(lock, [&] { return !queue_.empty() || finished_ || failed_; }); + if (failed_ || queue_.empty()) + return; + auto body = std::move(queue_.front()); + queue_.pop_front(); + lock.unlock(); + bool ok{}; + try { + ok = bool(write_frame(stream_, body)); + } catch (const std::exception &) { + } + lock.lock(); + bytes_ -= body.size(); + if (!ok) { + failed_ = true; + return; + } + } + } +}; + +Json error_payload(std::int64_t code, std::string_view message) { + return Json{Json::Object{{"code", Json{code}}, {"message", Json{std::string{message}}}}}; } -DispatchResult error(std::string_view id, int code, std::string_view message) { - return {.response = "{\"jsonrpc\":\"2.0\",\"id\":" + std::string{id} + ",\"error\":{\"code\":" + - std::to_string(code) + ",\"message\":" + quote_json(message) + "}}", - .exit_code = std::nullopt}; +DispatchResult reply(const Json &id, std::string key, Json payload) { + Json::Object envelope{{"jsonrpc", Json{std::string{"2.0"}}}, {"id", id}}; + envelope.emplace(std::move(key), std::move(payload)); + auto body = Protocol::serialize_json(Json{std::move(envelope)}); + if (body) + return {.response = std::move(*body), .exit_code = std::nullopt}; + + auto fallback = Protocol::serialize_json( + Json{Json::Object{{"jsonrpc", Json{std::string{"2.0"}}}, + {"id", id}, + {"error", error_payload(-32603, "Internal error")}}}); + if (fallback) + return {.response = std::move(*fallback), + .exit_code = std::nullopt, + .diagnostic = "failed to encode response"}; + return {.response = std::nullopt, .exit_code = 1, .diagnostic = "failed to encode response ID"}; } -DispatchResult result(std::string_view id, std::string_view value) { - return {.response = "{\"jsonrpc\":\"2.0\",\"id\":" + std::string{id} + - ",\"result\":" + std::string{value} + "}", - .exit_code = std::nullopt}; +DispatchResult error(const Json &id, std::int64_t code, std::string_view message) { + return reply(id, "error", error_payload(code, message)); } } // namespace +Server::Server(WorkspaceLaunch launch, std::function send) : workspace_(launch) { + if (launch.root && launch.diagnostics_profile && send) + diagnostics_ = std::make_unique( + *launch.root, std::move(launch.diagnostics_profile), workspace_, documents_, + std::move(send)); +} +Server::~Server() = default; + DispatchResult Server::handle(std::string_view body) { auto parsed = parse_json(body); if (!parsed) - return error("null", -32700, "Parse error"); + return error(Json{nullptr}, -32700, "Parse error"); const auto *object = std::get_if(&parsed->value); if (!object) - return error("null", -32600, "Invalid Request"); + return error(Json{nullptr}, -32600, "Invalid Request"); - const auto *id_value = member(*object, "id"); - const auto *method_value = member(*object, "method"); - const auto *method = string(method_value); - const auto *version = string(member(*object, "jsonrpc")); - const auto *params = member(*object, "params"); - const auto *result_value = member(*object, "result"); - const auto *error_value = member(*object, "error"); + const auto *id_value = find_member(*object, "id"); + const auto *method_value = find_member(*object, "method"); + const auto *method = as_string(method_value); + const auto *version = as_string(find_member(*object, "jsonrpc")); + const auto *params = find_member(*object, "params"); + const auto *result_value = find_member(*object, "result"); + const auto *error_value = find_member(*object, "error"); // This shell issues no requests. Valid peer responses are unmatched and // must be ignored, including errors whose correlation ID is null. @@ -55,9 +152,9 @@ DispatchResult Server::handle(std::string_view body) { request_id(*id_value).has_value(); bool valid_payload = result_value != nullptr; if (error_value) { - if (const auto *details = std::get_if(&error_value->value)) { - if (const auto *code = member(*details, "code"); - code && string(member(*details, "message"))) { + if (const auto *details = as_object(error_value)) { + if (const auto *code = find_member(*details, "code"); + code && as_string(find_member(*details, "message"))) { const auto checked = request_id(*code); valid_payload = checked && std::holds_alternative(*checked); } @@ -68,23 +165,66 @@ DispatchResult Server::handle(std::string_view body) { } const bool notification = !id_value; - std::string id{"null"}; + Json id{nullptr}; if (id_value) { auto checked = request_id(*id_value); if (!checked) - return error("null", -32600, "Invalid Request"); - id = encode_id(*checked); + return error(Json{nullptr}, -32600, "Invalid Request"); + id = Protocol::request_id_json(std::move(*checked)); } if (!version || *version != "2.0" || !method || result_value || error_value) { // Method-bearing objects without IDs are notifications, even when // malformed. They must never elicit a response. + if (notification && method && *method == "textDocument/didChange" && + state_ == State::running) { + if (diagnostics_) + diagnostics_->begin_update(); + reject_change_envelope(documents_, params); + if (diagnostics_) + diagnostics_->finish_update(); + return {.response = std::nullopt, + .exit_code = std::nullopt, + .diagnostic = "invalid didChange envelope"}; + } if (notification && method_value) return {}; return error(id, -32600, "Invalid Request"); } if (notification) { - if (*method == "exit") + if (*method == "exit") { + if (diagnostics_) + diagnostics_->stop(); return {.response = std::nullopt, .exit_code = state_ == State::shutdown ? 0 : 1}; + } + if (state_ == State::running) { + if (*method == "workspace/didChangeWorkspaceFolders" || + *method == "workspace/didChangeConfiguration") { + if (diagnostics_) + diagnostics_->begin_update(); + auto updated = *method == "workspace/didChangeWorkspaceFolders" + ? workspace_.update_folders(params) + : workspace_.configure(params); + if (diagnostics_) + diagnostics_->finish_update(true); + if (!updated) + return {.response = std::nullopt, + .exit_code = std::nullopt, + .diagnostic = updated.error().substr(0, 256)}; + return {}; + } + const bool change = *method == "textDocument/didOpen" || + *method == "textDocument/didChange" || + *method == "textDocument/didClose"; + if (diagnostics_ && change) + diagnostics_->begin_update(); + auto synced = synchronize_document(documents_, *method, params); + if (diagnostics_ && change) + diagnostics_->finish_update(); + if (!synced) + return {.response = std::nullopt, + .exit_code = std::nullopt, + .diagnostic = synced.error().substr(0, 256)}; + } return {}; } if (state_ == State::shutdown) @@ -96,27 +236,181 @@ DispatchResult Server::handle(std::string_view body) { return error(id, -32600, "Invalid Request"); if (!params || !std::holds_alternative(params->value)) return error(id, -32602, "initialize params must be an object"); - state_ = State::running; - return result(id, "{\"capabilities\":{},\"serverInfo\":{\"name\":\"VoidLanguageServer\"," - "\"version\":\"0.1.0\"}}"); + if (auto configured = workspace_.initialize(*params); !configured) + return error(id, -32602, configured.error().substr(0, 256)); + const auto encoding = negotiate_position_encoding(*params); + if (!documents_.set_position_encoding(encoding)) + return error(id, -32603, "Could not set document position encoding"); + if (diagnostics_) { + const auto *cap = member(member(member(params, "capabilities"), "textDocument"), + "publishDiagnostics"); + diagnostics_->set_version_support( + Protocol::as_bool(member(cap, "versionSupport")).value_or(false)); + const auto *edit = + member(member(member(params, "capabilities"), "workspace"), "workspaceEdit"); + diagnostics_->set_transactional_rename( + Protocol::as_bool(member(edit, "documentChanges")).value_or(false)); + } + Json::Object sync{{"openClose", Json{true}}, {"change", Json{std::int64_t{2}}}}; + Json::Object capabilities{ + {"positionEncoding", + Json{std::string{Void::LanguageServer::Documents::encoding_name(encoding)}}}, + {"textDocumentSync", Json{std::move(sync)}}, + {"workspace", + Json{Json::Object{ + {"workspaceFolders", Json{Json::Object{{"supported", Json{true}}, + {"changeNotifications", Json{true}}}}}}}}}; + if (diagnostics_ && diagnostics_->supports_occurrences()) { + capabilities.emplace("hoverProvider", Json{true}); + capabilities.emplace("definitionProvider", Json{true}); + } + if (diagnostics_) + capabilities.emplace("completionProvider", + Json{Json::Object{{"triggerCharacters", Json{Json::Array{}}}, + {"resolveProvider", Json{true}}}}); + if (diagnostics_ && diagnostics_->supports_occurrences()) + capabilities.emplace("signatureHelpProvider", + Json{Json::Object{{"triggerCharacters", + Json{Json::Array{Json{std::string{"("}}, + Json{std::string{","}}}}}}}); + Json::Object info{{"name", Json{std::string{"VoidLanguageServer"}}}, + {"version", Json{std::string{server_version}}}}; + auto initialized = reply(id, "result", + Json{Json::Object{{"capabilities", Json{std::move(capabilities)}}, + {"serverInfo", Json{std::move(info)}}}}); + if (initialized.diagnostic.empty()) + state_ = State::running; + return initialized; } if (params && !std::holds_alternative(params->value) && !std::holds_alternative(params->value) && !std::holds_alternative(params->value)) return error(id, -32600, "Invalid Request"); + if (*method == "voidLanguageServer/providerStatus") { + auto status = workspace_.provider_status(params); + if (!status) + return error(id, -32602, status.error().substr(0, 256)); + return reply(id, "result", std::move(*status)); + } + if (*method == "voidLanguageServer/analysisStatus") { + const auto *uri = as_string(member(member(params, "textDocument"), "uri")); + if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri)) + return error(id, -32602, "Expected textDocument.uri"); + return reply(id, "result", + diagnostics_ ? diagnostics_->status(*uri) + : Json{Json::Object{{"state", Json{std::string{"disabled"}}}}}); + } + if (*method == "textDocument/hover" || *method == "textDocument/definition" || + *method == "textDocument/signatureHelp") { + if (!diagnostics_ || !diagnostics_->supports_occurrences()) + return error(id, -32601, "Method not found"); + const auto *uri = as_string(member(member(params, "textDocument"), "uri")); + const auto *position = member(params, "position"); + const auto *line = position ? member(position, "line") : nullptr; + const auto *character = position ? member(position, "character") : nullptr; + const auto *line_value = line ? std::get_if(&line->value) : nullptr; + const auto *character_value = + character ? std::get_if(&character->value) : nullptr; + if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !line_value || + !character_value || *line_value < 0 || *character_value < 0 || + *line_value > Void::LanguageServer::Documents::kMaxPositionValue || + *character_value > Void::LanguageServer::Documents::kMaxPositionValue) + return error(id, -32602, "Expected textDocument.uri and a bounded position"); + const Void::LanguageServer::Documents::Position selected{ + static_cast(*line_value), static_cast(*character_value)}; + auto result = *method == "textDocument/hover" ? diagnostics_->hover(*uri, selected) + : *method == "textDocument/definition" + ? diagnostics_->definition(*uri, selected) + : diagnostics_->signature_help(*uri, selected); + return reply(id, "result", std::move(result)); + } + if (*method == "completionItem/resolve") { + if (!diagnostics_) + return error(id, -32601, "Method not found"); + if (!params) + return error(id, -32602, "Expected a completion item"); + return reply(id, "result", diagnostics_->completion_resolve(*params)); + } + if (*method == "textDocument/completion") { + if (!diagnostics_) + return error(id, -32601, "Method not found"); + const auto *uri = as_string(member(member(params, "textDocument"), "uri")); + const auto *position = member(params, "position"); + const auto *line = position ? member(position, "line") : nullptr; + const auto *character = position ? member(position, "character") : nullptr; + const auto *line_value = line ? std::get_if(&line->value) : nullptr; + const auto *character_value = + character ? std::get_if(&character->value) : nullptr; + if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !line_value || + !character_value || *line_value < 0 || *character_value < 0 || + *line_value > Void::LanguageServer::Documents::kMaxPositionValue || + *character_value > Void::LanguageServer::Documents::kMaxPositionValue) + return error(id, -32602, "Expected textDocument.uri and a bounded position"); + return reply( + id, "result", + diagnostics_->completion(*uri, {static_cast(*line_value), + static_cast(*character_value)})); + } + if (*method == "textDocument/references" || *method == "textDocument/prepareRename" || + *method == "textDocument/rename") { + if (!diagnostics_ || !diagnostics_->supports_occurrences()) + return error(id, -32601, "Method not found"); + const auto *uri = as_string(member(member(params, "textDocument"), "uri")); + const auto *position = member(params, "position"); + const auto *line = position ? member(position, "line") : nullptr; + const auto *character = position ? member(position, "character") : nullptr; + const auto *line_value = line ? std::get_if(&line->value) : nullptr; + const auto *character_value = + character ? std::get_if(&character->value) : nullptr; + if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !line_value || + !character_value || *line_value < 0 || *character_value < 0 || + *line_value > Void::LanguageServer::Documents::kMaxPositionValue || + *character_value > Void::LanguageServer::Documents::kMaxPositionValue) + return error(id, -32602, "Expected textDocument.uri and a bounded position"); + const Void::LanguageServer::Documents::Position selected{ + static_cast(*line_value), static_cast(*character_value)}; + semantic::EditorDiagnostics::NavigationReply navigation; + if (*method == "textDocument/references") + navigation = diagnostics_->references(*uri, selected); + else if (*method == "textDocument/prepareRename") + navigation = diagnostics_->prepare_rename(*uri, selected); + else { + const auto *name = as_string(member(params, "newName")); + if (!name || name->size() > 256) + return error(id, -32602, "Expected a bounded newName"); + navigation = diagnostics_->rename(*uri, selected, *name); + } + if (navigation.refusal) + return error(id, -32803, navigation.refusal->substr(0, 256)); + return reply(id, "result", std::move(navigation.result)); + } + if (*method == "workspace/symbol") { + if (!diagnostics_ || !diagnostics_->supports_occurrences()) + return error(id, -32601, "Method not found"); + const auto *query = as_string(member(params, "query")); + if (!query || query->size() > 256) + return error(id, -32602, "Expected a bounded workspace symbol query"); + return reply(id, "result", diagnostics_->workspace_symbols(*query)); + } if (*method == "shutdown") { if (params && !std::holds_alternative(params->value)) return error(id, -32602, "shutdown takes no params"); - state_ = State::shutdown; - return result(id, "null"); + auto stopped = reply(id, "result", Json{nullptr}); + if (diagnostics_) + diagnostics_->stop(); + if (stopped.diagnostic.empty()) + state_ = State::shutdown; + return stopped; } return error(id, -32601, "Method not found"); } int run_stdio(std::istream &input, std::ostream &output, std::ostream &diagnostics, - FrameLimits limits) { + FrameLimits limits, WorkspaceLaunch launch) { try { - Server server; + Output egress{output, bool(launch.diagnostics_profile)}; + Server server{std::move(launch), + [&](std::string body) { return egress.send(std::move(body)); }}; for (;;) { auto frame = read_frame(input, limits); if (!frame) { @@ -128,15 +422,16 @@ int run_stdio(std::istream &input, std::ostream &output, std::ostream &diagnosti return 1; } auto dispatched = server.handle(**frame); + if (!dispatched.diagnostic.empty()) + diagnostics << "vls: " << dispatched.diagnostic << '\n'; if (dispatched.response) { - const auto written = write_frame(output, *dispatched.response); - if (!written) { - diagnostics << "vls: " << written.error() << '\n'; + if (!egress.send(std::move(*dispatched.response))) { + diagnostics << "vls: failed to write protocol frame\n"; return 1; } } if (dispatched.exit_code) - return *dispatched.exit_code; + return egress.finish() ? *dispatched.exit_code : 1; } } catch (const std::exception &) { diagnostics << "vls: failed to process protocol stream\n"; diff --git a/src/Workspace/Configuration.cpp b/src/Workspace/Configuration.cpp new file mode 100644 index 0000000..f0f7f14 --- /dev/null +++ b/src/Workspace/Configuration.cpp @@ -0,0 +1,467 @@ +#include + +#include + +#include +#include +#include +#include + +namespace Void::LanguageServer::Workspace { +namespace { +namespace fs = std::filesystem; +using Protocol::Json; + +constexpr std::size_t max_entries = 256; +constexpr std::size_t max_configuration_bytes = 1024 * 1024; +std::atomic trusted_input_revision{}; + +struct Limit { + std::string_view key; + std::optional SettingsOverrides::*member; + std::uint32_t minimum, maximum, workspace_ceiling; +}; +constexpr ResourceLimitsConfig defaults; +constexpr Limit limits[] = { + {"maxSemanticWorkers", &SettingsOverrides::max_semantic_workers, 1, 64, + defaults.max_semantic_workers}, + {"workerMemoryLimitMib", &SettingsOverrides::worker_memory_limit_mib, 128, 65536, + defaults.worker_memory_limit_mib}, + {"maxResponseFileDepth", &SettingsOverrides::max_response_file_depth, 1, 32, + defaults.max_response_file_depth}, + {"maxResponseFileBytes", &SettingsOverrides::max_response_file_bytes, 1, 16 * 1024 * 1024, + defaults.max_response_file_bytes}, + {"maxCompdbBytes", &SettingsOverrides::max_compdb_bytes, 1, 1024 * 1024 * 1024, + defaults.max_compdb_bytes}, + {"maxManifestBytes", &SettingsOverrides::max_manifest_bytes, 1, 1024 * 1024 * 1024, + defaults.max_manifest_bytes}, +}; + +bool security_key(std::string_view key) { + constexpr std::string_view names[]{"toolApprovals", "trustedRoots", + "approvedCompilers", "approvedWrappers", + "allowMetadataRefresh", "allowExplicitBuildActions", + "allowCompilerPlugins"}; + return std::ranges::contains(names, key); +} + +bool valid_text(std::string_view text) { + return !text.empty() && text.size() <= 4095 && text.find('\0') == text.npos; +} + +std::optional resolve(const fs::path &base, const fs::path &raw) { + if (!Detail::valid_path(raw)) { + return std::nullopt; + } + auto path = base / raw; + // Keep symlink components, including those followed by "..", as the user selected them. + return Detail::valid_path(path) ? std::optional{std::move(path)} : std::nullopt; +} + +std::optional directory(const fs::path &path) { + std::error_code ec; + auto result = fs::canonical(path, ec); + if (ec || !fs::is_directory(result, ec)) { + return std::nullopt; + } + return result; +} + +std::optional operation(std::string_view name) { + if (name == "metadataRefresh") + return AuthorityLevel::trusted_metadata_refresh; + if (name == "compilerUse") + return AuthorityLevel::compiler_use; + if (name == "explicitBuildAction") + return AuthorityLevel::explicit_build_action; + return std::nullopt; +} + +std::optional> read_approvals(const Json &node) { + const auto *rows = Protocol::as_array(&node); + if (!rows || rows->size() > max_entries) + return std::nullopt; + std::vector result; + for (const auto &row : *rows) { + const auto *obj = Protocol::as_object(&row); + if (!obj || obj->size() != 3) + return std::nullopt; + const auto *root = Protocol::as_string(Protocol::find_member(*obj, "root")); + const auto *op = Protocol::as_string(Protocol::find_member(*obj, "operation")); + const auto *exe = Protocol::as_string(Protocol::find_member(*obj, "executable")); + if (!root || !op || !exe || !valid_text(*root) || !valid_text(*exe)) + return std::nullopt; + const auto kind = operation(*op); + if (!kind) + return std::nullopt; + result.push_back({*root, *kind, *exe}); + } + return result; +} + +template std::optional> read_strings(const Json &node) { + const auto *array = Protocol::as_array(&node); + if (!array || array->size() > max_entries) + return std::nullopt; + std::vector result; + for (const auto &value : *array) { + const auto *str = Protocol::as_string(&value); + if (!str || !valid_text(*str)) + return std::nullopt; + result.emplace_back(*str); + } + return result; +} + +SettingsOverrides read_fields(const Json &json, ConfigLayer source, + std::vector &diagnostics) { + SettingsOverrides out; + auto report = [&](std::string_view key, std::string message, + ConfigIssue issue = ConfigIssue::invalid_value) { + diagnostics.push_back({source, std::string(key.substr(0, 96)), std::move(message), issue}); + }; + const auto *obj = Protocol::as_object(&json); + if (obj) { + if (const auto *nested = Protocol::find_member(*obj, "voidLanguageServer")) { + obj = Protocol::as_object(nested); + } + } + if (!obj || obj->size() > 64) { + report("", "settings must be an object of at most 64 fields"); + out.tool_approvals.emplace(); + return out; + } + for (const auto &[key, value] : *obj) { + if (source == ConfigLayer::workspace_local && security_key(key)) { + report(key, "only the launcher can select execution settings", + ConfigIssue::untrusted_setting); + continue; + } + const auto limit = std::ranges::find(limits, key, &Limit::key); + if (limit != std::end(limits)) { + // Resource allocation requires an integer token; a rounded JSON double is ambiguous. + const auto *integer = std::get_if(&value.value); + if (integer && std::in_range(*integer)) { + out.*(limit->member) = static_cast(*integer); + } else { + report(key, "expected an unsigned integer"); + } + continue; + } + if (key == "provider") { + const auto *name = Protocol::as_string(&value); + for (auto pref : {ProviderPreference::auto_detect, ProviderPreference::vbs, + ProviderPreference::compdb, ProviderPreference::none}) { + if (name && provider_preference_name(pref) == *name) + out.provider = pref; + } + if (!out.provider) + report(key, "expected auto, vbs, compdb or none"); + } else if (key == "vbsManifestPath" || key == "compdbPath" || key == "selectedProfile") { + const auto *text = Protocol::as_string(&value); + if (!text || !valid_text(*text)) + report(key, "expected a bounded non-empty string"); + else if (key == "vbsManifestPath") + out.vbs_manifest_path = *text; + else if (key == "compdbPath") + out.compdb_path = *text; + else + out.selected_profile = *text; + } else if (key == "enableBackgroundIndexing" || key == "allowMetadataRefresh" || + key == "allowExplicitBuildActions" || key == "allowCompilerPlugins") { + const auto flag = Protocol::as_bool(&value); + if (!flag) + report(key, "expected a boolean"); + else if (key == "enableBackgroundIndexing") + out.enable_background_indexing = flag; + else if (key == "allowMetadataRefresh") + out.allow_metadata_refresh = flag; + else if (key == "allowExplicitBuildActions") + out.allow_explicit_build_actions = flag; + else + out.allow_compiler_plugins = flag; + } else if (key == "trustedRoots" || key == "approvedCompilers") { + auto &field = key == "trustedRoots" ? out.trusted_roots : out.approved_compilers; + field = read_strings(value); + if (!field) + report(key, "expected an array of at most 256 non-empty paths"); + } else if (key == "approvedWrappers") { + out.approved_wrappers = read_strings(value); + if (!out.approved_wrappers) + report(key, "expected an array of supported wrapper names"); + } else if (key == "toolApprovals") { + out.tool_approvals = read_approvals(value); + if (!out.tool_approvals) + report(key, "expected at most 256 exact root, operation and executable triples"); + } else { + report(key, "unknown workspace setting", ConfigIssue::unsupported); + } + } + return out; +} + +} // namespace + +std::uint64_t PartialWorkspaceSettings::latest_trusted_revision() noexcept { + return trusted_input_revision.load(); +} + +PartialWorkspaceSettings::PartialWorkspaceSettings(ConfigOrigin origin, SettingsOverrides values, + std::vector diagnostics) + : origin_(std::move(origin)), values_(std::move(values)), diagnostics_(std::move(diagnostics)) { + const auto source = origin_.layer; + auto report = [&](std::string_view key, std::string message, + ConfigIssue issue = ConfigIssue::invalid_value) { + diagnostics_.push_back({source, std::string(key), std::move(message), issue}); + }; + if (!Detail::valid_path(origin_.base) || !origin_.base.is_absolute()) { + report("", "an explicit absolute configuration base is required", + ConfigIssue::invalid_origin); + origin_.base.clear(); + values_ = {}; + values_.tool_approvals.emplace(); + return; + } + if (source == ConfigLayer::workspace_local) { + // Resolve the root once so that a later symlink retarget cannot move this configuration. + const auto canonical = directory(origin_.base); + if (!canonical) { + report("", "workspace root must be an existing directory", ConfigIssue::invalid_origin); + origin_.base.clear(); + values_ = {}; + return; + } + origin_.base = *canonical; + } + if (values_.provider && provider_preference_name(*values_.provider).empty()) { + values_.provider.reset(); + report("provider", "unsupported provider preference"); + } + for (const auto &limit : limits) { + auto &field = values_.*(limit.member); + if (!field) + continue; + if (*field < limit.minimum || *field > limit.maximum) { + report(limit.key, "value must be between " + std::to_string(limit.minimum) + " and " + + std::to_string(limit.maximum)); + field.reset(); + } else if (source == ConfigLayer::workspace_local && *field > limit.workspace_ceiling) { + field = limit.workspace_ceiling; + report(limit.key, + "workspace value exceeds the runtime ceiling of " + + std::to_string(limit.workspace_ceiling), + ConfigIssue::resource_limit); + } + } + auto bind_path = [&](std::optional &field, std::string_view key) { + if (!field) + return; + field = resolve(origin_.base, *field); + if (!field) + report(key, "invalid configured path"); + }; + bind_path(values_.vbs_manifest_path, "vbsManifestPath"); + bind_path(values_.compdb_path, "compdbPath"); + if (values_.selected_profile && !valid_text(*values_.selected_profile)) { + values_.selected_profile.reset(); + report("selectedProfile", "expected a bounded non-empty profile"); + } + auto bind_paths = [&](std::optional> &list, std::string_view key) { + if (!list) + return; + if (list->size() <= max_entries) { + for (auto &path : *list) { + auto resolved = resolve(origin_.base, path); + if (!resolved) { + list.reset(); + report(key, "invalid configured path"); + return; + } + path = std::move(*resolved); + } + } else { + list.reset(); + report(key, "too many configured paths"); + } + }; + bind_paths(values_.trusted_roots, "trustedRoots"); + bind_paths(values_.approved_compilers, "approvedCompilers"); + if (values_.approved_wrappers && + (values_.approved_wrappers->size() > max_entries || + !std::ranges::all_of(*values_.approved_wrappers, is_transparent_wrapper))) { + values_.approved_wrappers.emplace(); + report("approvedWrappers", "only ccache, sccache and distcc data prefixes are supported"); + } + if (values_.allow_compiler_plugins.value_or(false)) { + values_.allow_compiler_plugins = false; + report("allowCompilerPlugins", "compiler plugins are unsupported", + ConfigIssue::unsupported); + } + if (values_.tool_approvals) { + auto bind = [&](ToolSelection &entry) { + if (entry.operation != AuthorityLevel::compiler_use && + entry.operation != AuthorityLevel::trusted_metadata_refresh && + entry.operation != AuthorityLevel::explicit_build_action) + return false; + auto root = resolve(origin_.base, entry.root); + auto executable = resolve(origin_.base, entry.executable); + if (!root || !executable) + return false; + auto canonical = directory(*root); + if (!canonical) + return false; + entry.root = std::move(*canonical); + entry.executable = std::move(*executable); + return true; + }; + if (values_.tool_approvals->size() > max_entries || + !std::ranges::all_of(*values_.tool_approvals, bind)) { + report("toolApprovals", "each approval requires an existing workspace directory, a " + "supported operation and a tool path"); + } + } + if (source != ConfigLayer::workspace_local && + std::ranges::any_of(diagnostics_, [](const auto &d) { + return d.issue == ConfigIssue::invalid_value && security_key(d.key); + })) { + // A malformed trusted replacement must not retain either its valid prefix or lower-layer + // grants. + values_.tool_approvals.emplace(); + } +} + +PartialWorkspaceSettings parse_workspace_settings(const Json &payload, + const fs::path &workspace_root) { + std::vector diagnostics; + auto values = read_fields(payload, ConfigLayer::workspace_local, diagnostics); + return {{ConfigLayer::workspace_local, workspace_root, std::nullopt, 0}, + std::move(values), + std::move(diagnostics)}; +} + +std::expected +read_user_settings(const fs::path &selected_file) { + const auto revision = ++trusted_input_revision; + std::string bytes; + const auto file = + Detail::read_regular(selected_file, max_configuration_bytes, false, [&](auto chunk) { + bytes.append(reinterpret_cast(chunk.data()), chunk.size()); + return true; + }); + if (!file) { + return std::unexpected(ConfigDiagnostic{ + ConfigLayer::user_runtime, "", + "select an absolute, readable regular user configuration file of at most 1 MiB", + ConfigIssue::file_error}); + } + auto json = Protocol::parse_json(bytes); + if (!json) + return std::unexpected(ConfigDiagnostic{ConfigLayer::user_runtime, "", json.error(), + ConfigIssue::invalid_value}); + std::vector diagnostics; + auto values = read_fields(*json, ConfigLayer::user_runtime, diagnostics); + return PartialWorkspaceSettings{ + {ConfigLayer::user_runtime, selected_file.parent_path(), selected_file, revision}, + std::move(values), + std::move(diagnostics)}; +} + +PartialWorkspaceSettings settings_from_cli(SettingsOverrides options, const fs::path &base) { + return { + {ConfigLayer::cli, base, std::nullopt, ++trusted_input_revision}, std::move(options), {}}; +} + +void MergedConfiguration::apply(const PartialWorkspaceSettings &layer, ConfigLayer expected) { + if (layer.origin_.layer != expected) { + diagnostics_.push_back({layer.origin_.layer, "", + "settings source does not match its merge position", + ConfigIssue::invalid_origin}); + return; + } + diagnostics_.insert(diagnostics_.end(), layer.diagnostics_.begin(), layer.diagnostics_.end()); + if (expected == ConfigLayer::workspace_local) + effective_.workspace_root = layer.origin_.base; + const auto &v = layer.values_; + auto set = [](auto &dst, const auto &src) { + if (src) + dst = *src; + }; + set(effective_.provider, v.provider); + if (v.vbs_manifest_path) { + effective_.vbs_manifest_path = v.vbs_manifest_path; + effective_.vbs_manifest_origin = layer.origin_; + } + if (v.compdb_path) { + effective_.compdb_path = v.compdb_path; + effective_.compdb_origin = layer.origin_; + } + set(effective_.selected_profile, v.selected_profile); + set(effective_.enable_background_indexing, v.enable_background_indexing); + set(effective_.limits.max_semantic_workers, v.max_semantic_workers); + set(effective_.limits.worker_memory_limit_mib, v.worker_memory_limit_mib); + set(effective_.limits.max_response_file_depth, v.max_response_file_depth); + set(effective_.limits.max_response_file_bytes, v.max_response_file_bytes); + set(effective_.limits.max_compdb_bytes, v.max_compdb_bytes); + set(effective_.limits.max_manifest_bytes, v.max_manifest_bytes); + if (expected == ConfigLayer::workspace_local) + return; + set(effective_.trusted_roots, v.trusted_roots); + set(effective_.approved_compilers, v.approved_compilers); + set(effective_.approved_wrappers, v.approved_wrappers); + set(metadata_refresh_, v.allow_metadata_refresh); + set(build_actions_, v.allow_explicit_build_actions); + if (v.tool_approvals) { + effective_.tool_approvals_origin = layer.origin_; + effective_.tool_approvals.clear(); + for (const auto &entry : *v.tool_approvals) { + if (entry.root == effective_.workspace_root) + effective_.tool_approvals.push_back(entry); + } + } +} + +MergedConfiguration merge_configuration(const PartialWorkspaceSettings &workspace, + const PartialWorkspaceSettings *user, + const PartialWorkspaceSettings *cli) { + MergedConfiguration merged; + merged.apply(workspace, ConfigLayer::workspace_local); + if (user) + merged.apply(*user, ConfigLayer::user_runtime); + if (cli) + merged.apply(*cli, ConfigLayer::cli); + auto &settings = merged.effective_; + auto selected = [&](AuthorityLevel op) { + return std::ranges::contains(settings.tool_approvals, op, &ToolSelection::operation); + }; + settings.allow_metadata_refresh = + merged.metadata_refresh_.value_or(selected(AuthorityLevel::trusted_metadata_refresh)); + settings.allow_explicit_build_actions = + merged.build_actions_.value_or(selected(AuthorityLevel::explicit_build_action)); + std::erase_if(settings.tool_approvals, [&](const auto &entry) { + return (entry.operation == AuthorityLevel::trusted_metadata_refresh && + !settings.allow_metadata_refresh) || + (entry.operation == AuthorityLevel::explicit_build_action && + !settings.allow_explicit_build_actions); + }); + return merged; +} + +std::string_view provider_preference_name(ProviderPreference pref) noexcept { + switch (pref) { + case ProviderPreference::auto_detect: + return "auto"; + case ProviderPreference::vbs: + return "vbs"; + case ProviderPreference::compdb: + return "compdb"; + case ProviderPreference::none: + return "none"; + } + return {}; +} + +bool is_transparent_wrapper(std::string_view name) noexcept { + return name == "ccache" || name == "sccache" || name == "distcc"; +} + +} // namespace Void::LanguageServer::Workspace diff --git a/src/Workspace/Trust.cpp b/src/Workspace/Trust.cpp new file mode 100644 index 0000000..50f476f --- /dev/null +++ b/src/Workspace/Trust.cpp @@ -0,0 +1,615 @@ +#include + +#include + +#include + +#include +#include + +namespace Void::LanguageServer::Workspace { +namespace { +namespace fs = std::filesystem; +using DirectoryId = std::pair; + +bool valid_digest(std::string_view hex) { + return hex.size() == 64 && std::ranges::all_of(hex, [](char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + }); +} + +TrustError file_error(Detail::FileError error) { + using enum Detail::FileError; + switch (error) { + case invalid_path: + return TrustError::invalid_path; + case unavailable: + return TrustError::unavailable_file; + case not_regular: + return TrustError::not_regular; + case not_executable: + return TrustError::not_executable; + case too_large: + return TrustError::too_large; + case changed: + return TrustError::identity_changed; + case sink_failed: + return TrustError::digest_unavailable; + } + return TrustError::unavailable_file; +} + +std::optional directory_id(const fs::path &path) { + if (!Detail::valid_path(path) || !path.is_absolute()) + return std::nullopt; + std::error_code ec; + struct stat info{}; + if (fs::canonical(path, ec).native() != path.native() || ec || + ::stat(path.c_str(), &info) != 0 || !S_ISDIR(info.st_mode)) + return std::nullopt; + return DirectoryId{info.st_dev, info.st_ino}; +} + +bool bounded_arguments(std::span argv) { + if (argv.size() > 4096) + return false; + std::size_t remaining = 1024 * 1024; + for (const auto &arg : argv) { + if (arg.size() > 64 * 1024 || arg.size() > remaining || arg.find('\0') != arg.npos) + return false; + remaining -= arg.size(); + } + return true; +} + +bool normalized_operand(std::string_view value) { + if (value.empty() || value.front() != '/' || value.size() > 4095) + return false; + const fs::path path{value}; + return path.lexically_normal().native() == value; +} + +bool macro_operand(std::string_view value, bool definition) { + const auto equals = value.find('='); + if (!definition && equals != value.npos) + return false; + const auto name = value.substr(0, equals); + auto first = [](char c) { + return c == '_' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); + }; + return !name.empty() && first(name.front()) && + std::ranges::all_of(name, [&](char c) { return first(c) || (c >= '0' && c <= '9'); }); +} + +bool supported_driver(const fs::path &selected, CompilerDriver driver) { + const auto name = selected.filename().string(); + const auto dash = name.find('-'); + const auto stem = std::string_view{name}.substr(0, dash); + if (dash != name.npos) { + auto version = std::string_view{name}.substr(dash + 1); + if (version.empty() || version.front() == '.' || version.back() == '.' || + version.contains("..") || !std::ranges::all_of(version, [](char c) { + return c == '.' || (c >= '0' && c <= '9'); + })) + return false; + } + if (driver == CompilerDriver::gcc) + return stem == "gcc" || stem == "g++" || stem == "cc" || stem == "c++"; + if (driver == CompilerDriver::clang) + return stem == "clang" || stem == "clang++" || stem == "cc" || stem == "c++"; + return false; +} + +bool simple_compiler_option(std::string_view arg, CompilerDriver driver) { + if (arg == "-freflection") + return driver == CompilerDriver::gcc; + constexpr std::string_view flags[]{"-c", + "-fsyntax-only", + "-pthread", + "-g", + "-g0", + "-g1", + "-g2", + "-g3", + "-O0", + "-O1", + "-O2", + "-O3", + "-Os", + "-Og", + "-Wall", + "-Wextra", + "-Wpedantic", + "-Werror", + "-fPIC", + "-fpic", + "-fPIE", + "-fpie", + "-fno-exceptions", + "-fno-rtti", + "-fmodules", + "-fmodules-ts", + "-fmodule-header"}; + if (std::ranges::contains(flags, arg)) + return true; + if (!arg.starts_with("-std=")) + return false; + constexpr std::string_view standards[]{ + "c89", "c99", "c11", "c17", "c23", "gnu89", "gnu99", + "gnu11", "gnu17", "gnu23", "c++98", "c++03", "c++11", "c++14", + "c++17", "c++20", "c++23", "c++26", "c++2c", "gnu++98", "gnu++03", + "gnu++11", "gnu++14", "gnu++17", "gnu++20", "gnu++23", "gnu++26", "gnu++2c"}; + return std::ranges::contains(standards, arg.substr(5)); +} + +std::optional invocation_directory(const BuildInvocation &invocation) { + auto has_identity = [](std::string_view id) { + return !id.empty() && id.size() <= 4095 && id.find('\0') == id.npos; + }; + if (!has_identity(invocation.input_identity) || + !has_identity(invocation.environment_identity) || + !bounded_arguments(invocation.arguments) || !Detail::valid_path(invocation.root) || + !Detail::valid_path(invocation.executable) || !invocation.executable.is_absolute() || + !Detail::valid_path(invocation.working_directory) || + !std::ranges::starts_with(invocation.working_directory, invocation.root)) + return std::nullopt; + return directory_id(invocation.working_directory); +} + +} // namespace + +std::string_view trust_error_message(TrustError error) noexcept { + using enum TrustError; + switch (error) { + case invalid_path: + return "select an absolute path without embedded NUL"; + case unavailable_file: + return "selected file is missing or unreadable"; + case not_regular: + return "select a regular executable file"; + case not_executable: + return "selected file lacks executable permission"; + case too_large: + return "selected executable exceeds the inspection limit"; + case digest_unavailable: + return "a complete SHA-256 identity is required"; + case identity_changed: + return "selected file changed; refresh its trusted selection"; + case untrusted_root: + return "workspace has no current trusted tool selections"; + case operation_not_approved: + return "select a tool for this operation in trusted settings"; + case tool_not_approved: + return "executable spelling is outside this operation's selections"; + case tool_not_pinned: + return "the launcher must pin the selected executable first"; + case stale_generation: + return "workspace authority changed; discard the old request"; + case explicit_action_required: + return "this operation requires an explicit build action"; + case invalid_invocation: + return "provide the complete bounded invocation with a canonical cwd inside its workspace"; + case action_pending: + return "finish or cancel the pending build action"; + case action_not_current: + return "the build approval is cancelled, spent or from another policy"; + case invocation_mismatch: + return "the invocation differs from the user's approved build"; + case capacity_exceeded: + return "too many workspaces have active tool selections"; + } + return "unknown trust failure"; +} + +std::expected inspect_tool_identity(const fs::path &executable) { + auto hasher = Crypto::Hasher::create(Crypto::HashAlgorithm::Sha256); + if (!hasher) + return std::unexpected(TrustError::digest_unavailable); + const auto file = Detail::read_regular(executable, max_tool_bytes, true, [&](auto chunk) { + return hasher->update(chunk).has_value(); + }); + if (!file) + return std::unexpected(file_error(file.error())); + auto digest = hasher->finalize(); + if (!digest || digest->size() != 32) + return std::unexpected(TrustError::digest_unavailable); + constexpr std::string_view alphabet = "0123456789abcdef"; + std::string hex; + hex.reserve(64); + for (const auto byte : *digest) { + const auto n = std::to_integer(byte); + hex += alphabet[n >> 4]; + hex += alphabet[n & 15]; + } + const auto &info = file->metadata; + return ToolIdentity{executable, + file->canonical_path, + info.st_dev, + info.st_ino, + static_cast(info.st_size), + info.st_mode, + info.st_uid, + info.st_gid, + std::move(hex)}; +} + +std::expected revalidate_tool_identity(const ToolIdentity &pinned) { + if (!valid_digest(pinned.content_hash_hex)) + return std::unexpected(TrustError::digest_unavailable); + auto current = inspect_tool_identity(pinned.selected_path); + if (!current) + return std::unexpected(current.error()); + if (*current != pinned) + return std::unexpected(TrustError::identity_changed); + return current; +} + +CommandSecurityReport classify_and_unwrap_command(std::span argv, + std::span recognized_wrappers, + const ToolIdentity &selected_compiler, + CompilerDriver driver) { + using enum FlagClassification; + auto refuse = [](FlagClassification issue, std::size_t index, std::string_view reason) { + return CommandSecurityReport{ + .classification = issue, .argument_index = index, .reason = reason}; + }; + if (argv.empty() || !bounded_arguments(argv) || recognized_wrappers.size() > 256) + return refuse(invalid_command, 0, "provide an argv within the count and byte limits"); + for (std::size_t i = 0; i < argv.size(); ++i) { + if (std::ranges::any_of(argv[i], [](unsigned char c) { return c < 32 || c == 127; })) + return refuse(invalid_command, i, + "control characters are unsupported in compiler arguments"); + } + if (!Detail::valid_path(selected_compiler.selected_path) || + !selected_compiler.selected_path.is_absolute() || + !valid_digest(selected_compiler.content_hash_hex)) + return refuse(unapproved_compiler_path, 0, + "select an absolute compiler with a complete SHA-256 identity"); + + std::size_t compiler = 0; + while (compiler < argv.size() && argv[compiler] != selected_compiler.selected_path.native()) { + const fs::path wrapper{argv[compiler]}; + const auto name = wrapper.filename().string(); + if (!is_transparent_wrapper(name) || (!wrapper.is_absolute() && wrapper != name) || + !std::ranges::contains(recognized_wrappers, name)) { + if (is_transparent_wrapper(name) || + std::ranges::contains(argv.subspan(compiler + 1), + selected_compiler.selected_path.native())) + return refuse(execution_bearing_wrapper, compiler, "unsupported wrapper prefix"); + return refuse(unapproved_compiler_path, compiler, + "argv requires the exact selected compiler spelling"); + } + ++compiler; + } + if (compiler == argv.size()) + return refuse(unapproved_compiler_path, compiler, + "missing selected compiler after wrapper"); + if (!supported_driver(selected_compiler.selected_path, driver)) + return refuse(unsupported_driver, compiler, + "select a supported GCC or Clang C/C++ driver dialect and spelling"); + + bool compile_only = false; + std::size_t sources = 0; + for (std::size_t i = compiler + 1; i < argv.size(); ++i) { + const std::string_view arg = argv[i]; + if (arg.starts_with('@')) + return refuse(unresolved_response_file, i, + "expand and identify the response file before classification"); + if (arg.starts_with("-fplugin") || arg.starts_with("-fpass-plugin") || arg == "-load" || + arg == "-plugin" || arg == "-add-plugin") + return refuse(execution_bearing_plugin, i, "compiler and pass plugins are unsupported"); + if (arg.starts_with("-wrapper")) + return refuse(execution_bearing_wrapper, i, + "compiler wrapper execution is unsupported"); + if (arg.starts_with("-specs") || arg.starts_with("--specs") || arg.starts_with("-B") || + arg.starts_with("-X") || arg.starts_with("-Wl,") || arg.starts_with("-Wa,") || + arg.starts_with("-Wp,") || arg.starts_with("--config") || + arg.starts_with("--driver-mode")) + return refuse( + suspicious_toolchain_override, i, + "driver overrides and forwarded options require a supported interpretation"); + if (simple_compiler_option(arg, driver)) { + compile_only |= arg == "-c" || arg == "-fsyntax-only"; + continue; + } + constexpr std::string_view operands[]{"-I", "-isystem", "-iquote", "-D", "-U", "-x"}; + const auto option = + std::ranges::find_if(operands, [&](auto name) { return arg.starts_with(name); }); + if (option != std::end(operands)) { + auto value = arg.substr(option->size()); + if (value.empty()) { + if (i + 1 == argv.size()) + return refuse(unsupported_operand, i, "missing compiler option operand"); + value = argv[++i]; + } + if (value.starts_with('@')) + return refuse(unresolved_response_file, i, "unexpanded response-file operand"); + bool valid; + if (*option == "-D" || *option == "-U") + valid = macro_operand(value, *option == "-D"); + else if (*option == "-x") + valid = value == "c" || value == "c++"; + else + valid = normalized_operand(value); + if (!valid) + return refuse(unsupported_operand, i, + "unsupported or unresolved compiler option operand"); + continue; + } + if (arg.starts_with('-')) + return refuse(unsupported_option, i, + "compiler option is outside the supported semantic grammar"); + constexpr std::string_view suffixes[]{".c", ".C", ".cc", ".cp", ".cpp", ".cxx", ".c++", + ".cppm", ".ixx", ".h", ".hh", ".hpp", ".hxx"}; + if (!normalized_operand(arg) || + !std::ranges::contains(suffixes, fs::path(arg).extension().string())) + return refuse(unsupported_operand, i, + "expected a normalized absolute C/C++ input path"); + ++sources; + } + if (!compile_only || sources != 1) + return refuse(invalid_command, compiler, + "expected one C/C++ input with -c or -fsyntax-only"); + CommandSecurityReport result{.allowed = true, + .classification = compiler ? transparent_wrapper : safe}; + result.unwrapped_wrappers.assign(argv.begin(), argv.begin() + compiler); + result.unwrapped_argv.assign(argv.begin() + compiler, argv.end()); + return result; +} + +TrustPolicy::TrustPolicy(RevocationCallback on_revocation) + : on_revocation_(std::move(on_revocation)) {} + +void TrustPolicy::notify(const fs::path &root, std::uint64_t generation) const { + if (on_revocation_) + on_revocation_(root, generation); +} + +std::expected +TrustPolicy::replace_configuration(const MergedConfiguration &configuration) { + const auto &settings = configuration.effective(); + const auto &root = settings.workspace_root; + const auto id = directory_id(root); + if (!id) { + revoke_root_authority(root); + return std::unexpected(TrustError::invalid_path); + } + RootState next{.directory = *id, + .origin = settings.tool_approvals_origin, + .approval_floor = settings.tool_approvals_origin.revision}; + if (settings.tool_approvals_origin.layer == ConfigLayer::user_runtime || + settings.tool_approvals_origin.layer == ConfigLayer::cli) { + for (const auto &approval : settings.tool_approvals) { + if (approval.root == root) + next.tools.try_emplace({approval.operation, approval.executable.native()}); + } + } + std::unique_lock lock(mutex_); + auto slot = roots_.find(root); + const bool replacing = slot != roots_.end(); + if (!replacing) { + if (next.tools.empty()) + return 0; // Passive workspace traffic creates no authority state. + // Retain each trusted root's revocation floor for the lifetime of this policy. + if (roots_.size() >= 256) + return std::unexpected(TrustError::capacity_exceeded); + slot = roots_.try_emplace(root).first; + } else { + auto &state = slot->second; + if (next.origin.revision != 0 && next.origin.revision < state.origin.revision) + return std::unexpected(TrustError::stale_generation); + if (next.tools.empty()) { + next.approval_floor = PartialWorkspaceSettings::latest_trusted_revision(); + if (state.tools.empty()) { + state.approval_floor = next.approval_floor; + return state.generation; + } + } else if (next.origin.revision <= state.approval_floor) { + if (next.origin.revision != state.origin.revision) + return std::unexpected(TrustError::stale_generation); + // Re-merging the same launcher input (for example after a didChangeConfiguration) + // can tighten a scope. Only a fresh trusted selection can reinstate a missing pin. + const auto removed = std::erase_if(state.tools, [&](const auto &entry) { + return state.directory != *id || !next.tools.contains(entry.first); + }); + const bool missing = state.tools.size() != next.tools.size(); + if (removed) { + state.pending.reset(); + state.approval_floor = PartialWorkspaceSettings::latest_trusted_revision(); + state.generation = ++last_generation_; + } + const auto generation = state.generation; + lock.unlock(); + if (removed) + notify(root, generation); + if (missing) + return std::unexpected(TrustError::stale_generation); + return generation; + } + } + const auto generation = ++last_generation_; + next.generation = generation; + slot->second = std::move(next); + lock.unlock(); + if (replacing) + notify(root, generation); + return generation; +} + +std::uint64_t TrustPolicy::generation(const fs::path &root) const { + std::lock_guard lock(mutex_); + auto slot = roots_.find(root); + return slot == roots_.end() ? 0 : slot->second.generation; +} + +void TrustPolicy::revoke_root_authority(const fs::path &root) { + std::unique_lock lock(mutex_); + auto slot = roots_.find(root); + if (slot == roots_.end()) + return; + slot->second.approval_floor = PartialWorkspaceSettings::latest_trusted_revision(); + if (slot->second.tools.empty()) + return; + slot->second.tools.clear(); + slot->second.pending.reset(); + const auto generation = slot->second.generation = ++last_generation_; + lock.unlock(); + notify(root, generation); +} + +std::expected +TrustPolicy::inspect_selected(const fs::path &root, AuthorityLevel purpose, + const fs::path &executable, + std::optional required_generation) { + if (!Detail::valid_path(root) || !root.is_absolute() || !Detail::valid_path(executable) || + !executable.is_absolute()) + return std::unexpected(TrustError::invalid_path); + std::unique_lock lock(mutex_); + auto slot = roots_.find(root); + if (slot == roots_.end() || slot->first.native() != root.native() || slot->second.tools.empty()) + return std::unexpected(TrustError::untrusted_root); + const auto generation = slot->second.generation; + if (required_generation && generation != *required_generation) + return std::unexpected(TrustError::stale_generation); + const Key key{purpose, executable.native()}; + auto selection = slot->second.tools.find(key); + if (selection == slot->second.tools.end()) { + auto other = slot->second.tools.lower_bound({key.first, {}}); + return std::unexpected(other != slot->second.tools.end() && other->first.first == key.first + ? TrustError::tool_not_approved + : TrustError::operation_not_approved); + } + const auto pinned = selection->second; + if (!pinned && required_generation) + return std::unexpected(TrustError::tool_not_pinned); + const auto expected_directory = slot->second.directory; + lock.unlock(); + + auto observed = pinned ? revalidate_tool_identity(*pinned) : inspect_tool_identity(executable); + const bool same_root = directory_id(root) == expected_directory; + + lock.lock(); + slot = roots_.find(root); + if (slot == roots_.end() || slot->second.generation != generation) + return std::unexpected(TrustError::stale_generation); + auto &state = slot->second; + auto ¤t_pin = state.tools.at(key); + // Concurrent first pins can finish in either order; a later observation must agree with the + // already committed identity. A transient failed first inspection cannot mint a pin. + if (observed && current_pin && *current_pin != *observed) + observed = std::unexpected(TrustError::identity_changed); + if (!same_root || !observed) { + const auto error = same_root ? observed.error() : TrustError::untrusted_root; + if (same_root && !current_pin) + return std::unexpected(error); + if (!same_root) + state.tools.clear(); + else + state.tools.erase(key); + state.pending.reset(); + state.approval_floor = PartialWorkspaceSettings::latest_trusted_revision(); + const auto revoked = state.generation = ++last_generation_; + lock.unlock(); + notify(root, revoked); + return std::unexpected(error); + } + if (!current_pin) + current_pin = *observed; + return ToolCheck{std::move(*observed), root, key.first, generation, state.origin}; +} + +std::expected +TrustPolicy::pin_approved_tool(const fs::path &root, AuthorityLevel purpose, const fs::path &exe) { + return inspect_selected(root, purpose, exe, std::nullopt); +} + +std::expected TrustPolicy::check_tool(const fs::path &root, + AuthorityLevel purpose, + const fs::path &exe, + std::uint64_t expected_generation) { + if (purpose == AuthorityLevel::explicit_build_action) + return std::unexpected(TrustError::explicit_action_required); + return inspect_selected(root, purpose, exe, expected_generation); +} + +bool BuildInvocation::operator==(const BuildInvocation &other) const { + return root.native() == other.root.native() && + executable.native() == other.executable.native() && + working_directory.native() == other.working_directory.native() && + arguments == other.arguments && input_identity == other.input_identity && + environment_identity == other.environment_identity && + trust_generation == other.trust_generation; +} + +std::expected +TrustPolicy::approve_build_action(const BuildInvocation &invocation) { + { + std::lock_guard lock(mutex_); + auto slot = roots_.find(invocation.root); + if (slot != roots_.end() && slot->second.generation == invocation.trust_generation && + slot->second.pending) + return std::unexpected(TrustError::action_pending); + } + const auto cwd = invocation_directory(invocation); + if (!cwd) + return std::unexpected(TrustError::invalid_invocation); + auto checked = inspect_selected(invocation.root, AuthorityLevel::explicit_build_action, + invocation.executable, invocation.trust_generation); + if (!checked) + return std::unexpected(checked.error()); + std::lock_guard lock(mutex_); + auto slot = roots_.find(invocation.root); + if (slot == roots_.end() || slot->second.generation != invocation.trust_generation) + return std::unexpected(TrustError::stale_generation); + if (slot->second.pending) + return std::unexpected(TrustError::action_pending); + slot->second.pending = std::make_shared(invocation); + return BuildApproval{slot->second.pending, *cwd}; +} + +std::expected +TrustPolicy::consume_build_action(const BuildApproval &approval, + const BuildInvocation &invocation) { + if (!approval.invocation_) + return std::unexpected(TrustError::action_not_current); + if (*approval.invocation_ != invocation) + return std::unexpected(TrustError::invocation_mismatch); + { + std::lock_guard lock(mutex_); + auto slot = roots_.find(invocation.root); + if (slot == roots_.end() || slot->second.pending != approval.invocation_) + return std::unexpected(TrustError::action_not_current); + } + if (invocation_directory(invocation) != approval.directory_) { + (void)cancel_build_action(approval); + return std::unexpected(TrustError::invalid_invocation); + } + auto checked = inspect_selected(invocation.root, AuthorityLevel::explicit_build_action, + invocation.executable, invocation.trust_generation); + if (!checked) + return std::unexpected(checked.error()); + if (directory_id(invocation.working_directory) != approval.directory_) { + (void)cancel_build_action(approval); + return std::unexpected(TrustError::invalid_invocation); + } + std::lock_guard lock(mutex_); + auto slot = roots_.find(invocation.root); + if (slot == roots_.end() || slot->second.pending != approval.invocation_ || + slot->second.generation != checked->trust_generation) + return std::unexpected(TrustError::action_not_current); + slot->second.pending.reset(); + return checked; +} + +bool TrustPolicy::cancel_build_action(const BuildApproval &approval) { + if (!approval.invocation_) + return false; + std::lock_guard lock(mutex_); + auto slot = roots_.find(approval.invocation_->root); + if (slot == roots_.end() || slot->second.pending != approval.invocation_) + return false; + slot->second.pending.reset(); + return true; +} + +} // namespace Void::LanguageServer::Workspace diff --git a/src/WorkspaceSession.cpp b/src/WorkspaceSession.cpp new file mode 100644 index 0000000..a28749e --- /dev/null +++ b/src/WorkspaceSession.cpp @@ -0,0 +1,1495 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls { +namespace { +namespace fs = std::filesystem; +namespace Build = Void::LanguageServer::Build; +namespace Docs = Void::LanguageServer::Documents; +namespace Protocol = Void::LanguageServer::Protocol; +namespace Workspace = Void::LanguageServer::Workspace; +using Build::FilePurpose; +using Build::ProviderHealth; +using Protocol::as_array; +using Protocol::as_object; +using Protocol::as_string; +using Protocol::find_member; +using Protocol::Json; +using Workspace::ProviderPreference; + +template using Result = std::expected; +using Binding = std::expected; + +constexpr std::size_t max_folders = 64; +constexpr std::size_t max_settings_bytes = 64 * 1024; +constexpr std::size_t max_status_entries = 16; +constexpr std::size_t max_semantic_routes = 32; +constexpr std::size_t vbs_pointer_bytes = 256 * 1024; +constexpr std::string_view file_uri_prefix = "file://"; + +bool is_null(const Json *value) { + return value && std::holds_alternative(value->value); +} + +bool below(const fs::path &path, const fs::path &root) { + const auto [prefix, rest] = std::mismatch(root.begin(), root.end(), path.begin(), path.end()); + return prefix == root.end() && rest != path.end(); +} + +// Dot components are harmless. Parent traversal may change the meaning of a symlink path. +fs::path normalize_locator(const fs::path &path) { + if (std::ranges::find(path, fs::path{".."}) != path.end()) + return path; + return path.lexically_normal(); +} + +Result file_uri_key(std::string_view uri) { + auto key = Docs::client_uri_key(uri); + if (!key || !key->starts_with(file_uri_prefix)) + return std::unexpected{"workspace URI must be a local file URI"}; + return key; +} + +Result folder_uri(const Json &folder) { + const auto *record = as_object(&folder); + const auto *uri = record ? as_string(find_member(*record, "uri")) : nullptr; + if (!uri) + return std::unexpected{"workspace folder must contain a file URI"}; + if (const auto *name = find_member(*record, "name"); name) { + const auto *text = as_string(name); + if (!text || text->size() > Docs::kMaxDocumentUriBytes || text->contains('\0')) + return std::unexpected{"workspace folder name must be a bounded string"}; + } + return file_uri_key(*uri); +} + +struct Address { + fs::path root; + std::string uri, client_key; +}; + +Result
resolve_folder(std::string key) { + auto path = Docs::client_file_path(key); + if (!path) + return std::unexpected{"workspace directory could not be decoded"}; + // Workspace roots must already exist. Weak canonicalization can erase a + // missing component followed by '..', even when the supplied route fails. + std::error_code error; + auto root = fs::canonical(fs::path{*path}, error); + if (error || !fs::is_directory(root, error) || error) + return std::unexpected{"workspace URI must identify an existing directory"}; + auto uri = Docs::path_to_file_uri(root); + if (!file_uri_key(uri)) + return std::unexpected{"workspace directory cannot be represented as a local file URI"}; + return Address{std::move(root), std::move(uri), std::move(key)}; +} + +struct ClientSettings { + Json::Object defaults; + std::map> workspaces; +}; + +Result parse_settings(const Json::Object &values, + const fs::path &root) { + if (values.size() > 64 || values.contains("workspaces") || + values.contains("voidLanguageServer")) + return std::unexpected{"invalid workspace settings object"}; + auto settings = Workspace::parse_workspace_settings(Json{values}, root); + for (const auto &diagnostic : settings.diagnostics()) { + if (diagnostic.issue == Workspace::ConfigIssue::invalid_value || + diagnostic.issue == Workspace::ConfigIssue::invalid_origin) { + if (!diagnostic.key.empty()) + return std::unexpected{diagnostic.key + " must be valid. " + diagnostic.message}; + return std::unexpected{diagnostic.message}; + } + } + if (settings.origin().base != root) + return std::unexpected{"workspace directory changed while resolving settings"}; + return settings; +} + +Result read_settings(const Json &setting) { + const auto *values = as_object(&setting); + if (!values || values->size() > 65) + return std::unexpected{"voidLanguageServer settings must be an object"}; + auto encoded = Protocol::serialize_json(setting); + if (!encoded || encoded->size() > max_settings_bytes) + return std::unexpected{"voidLanguageServer settings exceed the request limit"}; + + ClientSettings result; + for (const auto &[key, value] : *values) { + if (key != "workspaces") { + result.defaults.emplace(key, value); + continue; + } + const auto *folders = as_object(&value); + if (!folders || folders->size() > max_folders) + return std::unexpected{"workspaces must be a bounded object keyed by folder URI"}; + for (const auto &[uri, settings] : *folders) { + auto folder = file_uri_key(uri); + const auto *fields = as_object(&settings); + if (!folder || !fields) + return std::unexpected{"per-folder settings require a file URI and an object"}; + // Validate entries for roots that may be added later, without resolving the URI here. + if (auto checked = parse_settings(*fields, "/"); !checked) + return std::unexpected{checked.error()}; + if (!result.workspaces.emplace(std::move(*folder), *fields).second) + return std::unexpected{"duplicate per-folder settings URI"}; + } + } + if (auto checked = parse_settings(result.defaults, "/"); !checked) + return std::unexpected{checked.error()}; + return result; +} + +struct Source { + std::string_view provider; + fs::path path; + bool operator==(const Source &) const = default; +}; + +struct Configuration { + std::string client_values; + Workspace::MergedConfiguration merged; + Source vbs, compdb; + std::uint64_t generation; + std::optional trust_error; + + [[nodiscard]] bool permits(const Source &source) const { + const auto pref = merged.effective().provider; + return (source == vbs && + (pref == ProviderPreference::auto_detect || pref == ProviderPreference::vbs)) || + (source == compdb && + (pref == ProviderPreference::auto_detect || pref == ProviderPreference::compdb)); + } +}; + +using ActiveConfiguration = std::shared_ptr; + +struct LastGood { + Source source; + Json::Object identity; +}; + +struct ProviderBasis; +struct SemanticSlot; +using RouteKey = std::pair; + +struct Folder { + Address address; + Build::WorkspaceIdentity identity; + Binding binding; + ActiveConfiguration config; + std::uint64_t issued{}, trust_generation{}; + std::optional current_source; + std::shared_ptr last_good; + std::shared_ptr basis; + std::uint64_t semantic_issued{}; + std::map> semantic_routes; +}; + +using FolderMap = std::map>; + +auto find_folder(const FolderMap &folders, std::string_view key) { + return std::ranges::find_if(folders, [&](const auto &entry) { + const auto &address = entry.second->address; + return key == address.client_key || key == address.uri; + }); +} + +bool address_available(const FolderMap &folders, const Address &address) { + return find_folder(folders, address.uri) == folders.end() && + find_folder(folders, address.client_key) == folders.end(); +} + +Result issue_workspace_revision() { + static std::atomic_uint64_t latest{}; + auto current = latest.load(std::memory_order_relaxed); + do { + if (current == std::numeric_limits::max()) + return std::unexpected{"workspace revision limit reached"}; + } while (!latest.compare_exchange_weak(current, current + 1, std::memory_order_relaxed)); + return current + 1; +} + +struct Query { + std::optional workspace; + std::optional document; + fs::path document_spelling; +}; + +Result set_document(Query &query, std::string_view uri) { + auto identity = Docs::normalize_uri(uri); + if (!identity) + return std::unexpected{identity.error()}; + auto spelling = Docs::client_file_path(uri); + if (!spelling) + return std::unexpected{spelling.error()}; + query.document = std::move(*identity); + query.document_spelling = std::move(*spelling); + return {}; +} + +RouteKey route_key(const Query &query) { + return {query.document_spelling, query.workspace.has_value()}; +} + +struct SemanticSlot { + Query query; + std::uint64_t issued{}; + std::shared_ptr selector; + std::shared_ptr current; +}; + +Result read_query(const Json *params) { + if (!params || is_null(params)) + return Query{}; + const auto *object = as_object(params); + if (!object) + return std::unexpected{"providerStatus params must be an object"}; + + Query result; + if (const auto *workspace = find_member(*object, "workspaceUri")) { + const auto *uri = as_string(workspace); + if (!uri) + return std::unexpected{"workspaceUri must be a string"}; + auto key = file_uri_key(*uri); + if (!key) + return std::unexpected{key.error()}; + result.workspace = std::move(*key); + } + if (const auto *document = find_member(*object, "textDocument")) { + const auto *text = as_object(document); + const auto *uri = text ? as_string(find_member(*text, "uri")) : nullptr; + if (!uri) + return std::unexpected{"textDocument must contain a URI"}; + if (auto parsed = set_document(result, *uri); !parsed) + return std::unexpected{parsed.error()}; + } + return result; +} + +Result> workspace_for(const FolderMap &folders, const Query &query) { + if (query.workspace) { + const auto folder = find_folder(folders, *query.workspace); + if (folder == folders.end()) + return std::unexpected{"workspaceUri is not an active workspace"}; + return folder->second; + } + std::shared_ptr match; + for (const auto &[root, folder] : folders) { + if (query.document && !below(query.document->canonical_path, root)) + continue; + if (match) + return std::unexpected{"providerStatus requires a workspaceUri to disambiguate"}; + match = folder; + } + return match; +} + +struct Work { + std::shared_ptr owner; + ActiveConfiguration config; + std::uint64_t sequence, trust_generation; + std::shared_ptr basis; + std::uint64_t semantic_cutoff{}; + + [[nodiscard]] std::optional scope() const { + if (!owner->binding) + return {}; + auto scope = *owner->binding; + scope.limits = config->merged.effective().limits; + return scope; + } +}; + +struct Observation { + Source source; + Build::ProviderObservation result; + std::optional absent_selector; +}; + +bool native_generation_database(const fs::path &path) { + const auto generation = path.parent_path(); + const auto id = generation.filename().native(); + const auto generations = generation.parent_path(); + const auto editor = generations.parent_path(); + return path.filename() == "compile_commands.json" && id.size() == 16 && + id.find_first_not_of("0123456789abcdef") == id.npos && + generations.filename() == "generations" && editor.filename() == "editor" && + editor.parent_path().parent_path().filename() == "profiles"; +} + +Observation observe(const Work &work, const Build::ProviderScope *scope, + const std::optional &driver = {}) { + const auto preference = work.config->merged.effective().provider; + if (preference == ProviderPreference::none) + return {{"none", {}}, {.provider = "none", .health = ProviderHealth::disabled}}; + const auto &vbs = work.config->vbs; + const auto &compdb = work.config->compdb; + if (!scope) { + const auto &source = preference == ProviderPreference::compdb ? compdb : vbs; + const auto &issue = work.owner->binding.error(); + return {source, + {.provider = std::string{source.provider}, + .health = issue.code == "changed" ? ProviderHealth::changed + : ProviderHealth::unavailable, + .issues = {issue}}}; + } + if (preference == ProviderPreference::compdb) + return {compdb, Build::observe_compdb(*scope, compdb.path, driver)}; + auto native = Build::observe_vbs(*scope, vbs.path, driver); + if (preference == ProviderPreference::vbs || native.health != ProviderHealth::missing || + native.issues.size() != 1 || native.issues.front().code != "missing" || + native.issues.front().path != vbs.path) + return {vbs, std::move(native)}; + + auto fallback = Build::observe_compdb(*scope, compdb.path, driver); + for (const auto &file : fallback.inputs) { + if (file.purpose == FilePurpose::database && + native_generation_database(file.canonical_path)) { + fallback.health = ProviderHealth::unavailable; + fallback.generation.reset(); + fallback.issues = {{"vbs_managed_alias", + "Automatic fallback requires an ordinary compilation database", + file.logical_path}}; + break; + } + } + return {compdb, std::move(fallback), vbs.path}; +} + +bool uncaptured_lookup(const Build::ProviderIssue &issue, + const Build::ProviderObservation &observation) { + constexpr std::string_view lookup_codes[]{ + "missing", "missing_reference", "outside_scope", "invalid_path", + "unavailable", "not_regular", "too_large", "changed"}; + return std::ranges::contains(lookup_codes, issue.code) && + std::ranges::none_of(observation.inputs, + [&](const auto &file) { return file.logical_path == issue.path; }); +} + +bool selector_current(const Build::ProviderScope &scope, const Observation &observed) { + if (!observed.absent_selector) + return true; + const auto lookup = + Build::read_provider_file(scope, *observed.absent_selector, FilePurpose::selection, 0); + return !lookup && lookup.error().code == "missing"; +} + +enum class Evidence { current, provider_changed, command_changed }; + +Evidence check_evidence(const Build::ProviderScope &scope, const Observation &observed) { + const auto &result = observed.result; + if (!selector_current(scope, observed)) + return Evidence::provider_changed; + if (const auto changed = Build::changed_provider_input(scope, result)) { + const bool primary = std::ranges::any_of(result.inputs, [&](const auto &file) { + return file.purpose != FilePurpose::response && file.logical_path == *changed; + }); + return primary ? Evidence::provider_changed : Evidence::command_changed; + } + for (const auto &issue : result.issues) { + if (!uncaptured_lookup(issue, result)) + continue; + auto purpose = FilePurpose::database; + auto limit = scope.limits.max_compdb_bytes; + if (observed.source.provider == "vbs") { + if (issue.path == observed.source.path) + purpose = FilePurpose::selection; + else if (issue.path.filename() == "status.json") + purpose = FilePurpose::status; + else + purpose = FilePurpose::native_database; + if (purpose != FilePurpose::native_database) + limit = std::min(scope.limits.max_manifest_bytes, vbs_pointer_bytes); + } + if (issue.code == "missing" || issue.code == "missing_reference" || issue.code == "changed") + limit = 0; + auto lookup = Build::read_provider_file(scope, issue.path, purpose, limit); + if (lookup || lookup.error().code != issue.code) + return Evidence::provider_changed; + } + return Evidence::current; +} + +// Passive and checked imports have different model revisions. Their selector, +// status and database captures identify the common workspace transition. +struct ProviderBasis { + Source source; + ProviderHealth health; + std::optional ticket; + std::vector files; + std::uint64_t sequence{}; + + explicit ProviderBasis(const Observation &observed) + : source(observed.source), health(observed.result.health), + ticket(observed.result.selection_ticket) { + for (const auto &file : observed.result.inputs) { + if (file.purpose != FilePurpose::response) { + files.push_back(file); + files.back().bytes.reset(); + } + } + } + + bool matches(const ProviderBasis &other) const { + return source == other.source && health == other.health && ticket == other.ticket && + std::ranges::equal(files, other.files, [](const auto &a, const auto &b) { + return a.purpose == b.purpose && a.logical_path == b.logical_path && + a.canonical_path == b.canonical_path && a.content_id == b.content_id && + Build::same_provider_object(a, b); + }); + } + + void mark_changed() { + health = ProviderHealth::changed; + files.clear(); + } +}; + +bool files_current(const ProviderBasis &basis, const Build::ProviderScope *scope) { + return std::ranges::all_of(basis.files, [&](const auto &file) { + return scope && Build::provider_file_current(*scope, file); + }); +} + +bool basis_current(const Work &work, const Build::ProviderScope *scope) { + return !work.basis || files_current(*work.basis, scope); +} + +void replace_basis(Folder &folder, ProviderBasis next) { + const auto sequence = folder.basis ? folder.basis->sequence : 0; + next.sequence = sequence == std::numeric_limits::max() ? sequence : sequence + 1; + folder.basis = std::make_shared(std::move(next)); + for (const auto &[key, slot] : folder.semantic_routes) + slot->current.reset(); +} + +// Independent reads can jointly discover one transition. Two observed transitions +// fence pending work even if the latest files again resemble its original capture. +bool install_basis(const Work &work, const ProviderBasis &incoming, bool previous_current) { + auto &folder = *work.owner; + if (folder.semantic_routes.empty()) + return true; + const auto sequence = work.basis ? work.basis->sequence : 0; + if (folder.basis != work.basis) + return folder.basis && folder.basis->sequence > sequence && + folder.basis->sequence - sequence == 1 && folder.basis->matches(incoming); + if (!folder.basis || !previous_current || !folder.basis->matches(incoming)) { + if (sequence == std::numeric_limits::max()) + return false; + replace_basis(folder, incoming); + } + return true; +} + +struct SemanticPlan { + Build::ProviderScope scope; + Build::DriverInput driver; + Observation observed; + bool retired{}; // Read and written only under the owning session's mutex. +}; + +std::unexpected failure(SemanticContextIssue issue, std::string message) { + return std::unexpected{SemanticContextError{issue, std::move(message)}}; +} + +auto superseded() { + return failure(SemanticContextIssue::superseded, "The semantic context is no longer current"); +} + +// Bind a client folder alias through its admitted physical root. Other external +// spellings cannot supply a workspace-scoped document route. +Build::CommandPathLookup document_binding(const Query &query, const Folder &folder, + const Build::ProviderScope &scope) { + const auto &root = folder.identity.root; + auto path = query.document_spelling; + if (!below(path, root)) { + const auto admitted = Docs::client_file_path(folder.address.client_key); + if (admitted && below(path, *admitted)) + path = root / path.lexically_relative(*admitted); + } + return Build::inspect_command_path(scope, path, Build::CommandPathKind::file); +} + +bool document_current(const Query &query, const Build::ProviderScope &scope, + const Build::ProviderObservation &binding) { + const auto latest = Docs::normalize_uri(query.document->display_uri); + return latest && latest->canonical_path == query.document->canonical_path && + !Build::changed_provider_input(scope, binding); +} + +std::string bounded_text(std::string_view text, std::size_t limit) { + auto prefix = text.substr(0, limit); + // A provider's byte cap can land in the middle of a UTF-8 scalar. + for (int i = 0; i < 4 && !prefix.empty(); ++i) { + if (Void::Unicode::validate_utf8(prefix)) + return std::string{prefix}; + prefix.remove_suffix(1); + } + return {}; +} + +Json text_json(std::string_view text) { return Json{std::string{text}}; } + +Json::Object generation_fields(const Build::ProviderObservation &result) { + Json::Object fields{ + {"provider", Json{result.provider}}, + {"contextCount", Json{static_cast( + result.generation ? result.generation->contexts().size() : 0)}}}; + if (result.generation) + fields.emplace("generation", + Json{Void::Encoding::Url::encode(result.generation->identity().revision)}); + if (result.native_generation) + fields.emplace("nativeGeneration", Json{*result.native_generation}); + if (result.profile) + fields.emplace("profile", Json{*result.profile}); + if (result.selection_ticket && std::in_range(*result.selection_ticket)) + fields.emplace("ticket", Json{static_cast(*result.selection_ticket)}); + return fields; +} + +std::string_view health_name(ProviderHealth health) { + switch (health) { + case ProviderHealth::ready: + return "ready"; + case ProviderHealth::missing: + return "missing"; + case ProviderHealth::unavailable: + return "unavailable"; + case ProviderHealth::invalid: + return "invalid"; + case ProviderHealth::stale: + return "stale"; + case ProviderHealth::changed: + return "changed"; + case ProviderHealth::disabled: + return "disabled"; + } + return "unavailable"; +} + +std::string_view state_name(ProviderHealth health) { + switch (health) { + case ProviderHealth::changed: + return "stale"; + case ProviderHealth::unavailable: + case ProviderHealth::invalid: + return "degraded"; + default: + return health_name(health); + } +} + +Json::Array issue_fields(const std::vector &issues) { + Json::Array rows; + for (const auto &issue : issues | std::views::take(max_status_entries)) { + rows.push_back(Json{Json::Object{{"code", Json{bounded_text(issue.code, 64)}}, + {"message", Json{bounded_text(issue.message, 512)}}}}); + } + return rows; +} + +Json context_fields(const Build::BuildContext &context) { + const auto &key = context.key; + const auto role = key.role == Build::ContextRole::target ? "target" + : key.role == Build::ContextRole::host_description ? "hostDescription" + : "unknown"; + Json::Object row{{"owningTu", Json{Docs::path_to_file_uri(key.owning_tu)}}, + {"alternative", Json{key.alternative}}, + {"role", text_json(role)}}; + if (key.profile) + row.emplace("profile", Json{*key.profile}); + if (key.target) + row.emplace("target", Json{*key.target}); + return Json{std::move(row)}; +} + +auto select_context(Build::SelectionState &state, const Build::Generation &generation, + const std::optional &selected_profile) { + const auto &identity = generation->identity(); + std::optional editor; + if (selected_profile) + editor = + Build::EditorSelection{identity.workspace.root, identity.provider, selected_profile}; + return state.update(generation, {}, editor); +} + +void add_selection(Json::Object &status, const Query &query, const Build::Generation &generation, + const std::optional &selected_profile = {}) { + if (!query.document) + return; + Json selected{nullptr}; + Json::Array alternatives; + if (generation && !query.document->canonical_path.empty()) { + const auto &identity = generation->identity(); + Build::SelectionState state{identity.workspace, query.document->canonical_path}; + if (auto choice = select_context(state, generation, selected_profile); choice) { + if ((*choice)->selected) + selected = context_fields(*(*choice)->selected); + const auto candidates = (*choice)->alternatives(); + for (const auto *candidate : candidates | std::views::take(max_status_entries)) + alternatives.push_back(context_fields(*candidate)); + if (candidates.size() > max_status_entries) + status.emplace("alternativesTruncated", Json{true}); + } + } + status.emplace("selected", std::move(selected)); + status.emplace("alternatives", Json{std::move(alternatives)}); +} + +Json document_only(const Query &query) { + Json::Object status{ + {"workspaceUri", Json{nullptr}}, {"provider", text_json("none")}, + {"requestedProvider", text_json("none")}, {"state", text_json("documentOnly")}, + {"providerHealth", text_json("disabled")}, {"contextCount", Json{std::int64_t{0}}}, + {"issues", Json{Json::Array{}}}, {"warnings", Json{Json::Array{}}}}; + add_selection(status, query, {}); + return Json{std::move(status)}; +} + +Json workspace_status(const Work &work, const Observation &observed, const Query &query, + const std::shared_ptr &last_good, Json::Object fields) { + const auto &result = observed.result; + fields.emplace("workspaceUri", Json{work.owner->address.uri}); + fields.emplace("incarnation", Json{work.owner->identity.session}); + fields.emplace("requestedProvider", text_json(Workspace::provider_preference_name( + work.config->merged.effective().provider))); + fields.emplace("state", text_json(state_name(result.health))); + fields.emplace("providerHealth", text_json(health_name(result.health))); + fields.emplace("issues", Json{issue_fields(result.issues)}); + auto warnings = issue_fields(result.warnings); + for (const auto &diagnostic : work.config->merged.diagnostics()) { + if (warnings.size() == max_status_entries) + break; + warnings.emplace_back(Json::Object{{"code", text_json("configuration")}, + {"message", Json{bounded_text(diagnostic.message, 512)}}, + {"key", Json{bounded_text(diagnostic.key, 96)}}}); + } + if (work.config->trust_error && warnings.size() < max_status_entries) { + warnings.emplace_back(Json::Object{ + {"code", text_json("trust")}, + {"message", text_json(Workspace::trust_error_message(*work.config->trust_error))}}); + } + fields.emplace("warnings", Json{std::move(warnings)}); + if (last_good && result.health != ProviderHealth::ready && last_good->source == observed.source) + fields.emplace("lastGood", Json{last_good->identity}); + add_selection(fields, query, result.generation, + work.config->merged.effective().selected_profile); + return Json{std::move(fields)}; +} +} // namespace + +struct SemanticLeaseData { + Query query; + Build::ProviderObservation document_binding; + std::shared_ptr basis; + std::shared_ptr plan; + std::shared_ptr selector; + Build::Selection selection; + std::uint64_t configuration; + std::uint32_t worker_memory_limit_mib; +}; + +SemanticContextLease::SemanticContextLease(std::shared_ptr data) + : data_(std::move(data)) {} + +const Build::Selection &SemanticContextLease::selection() const { return data_->selection; } +const Build::SelectionState &SemanticContextLease::selection_state() const { + return *data_->selector; +} +const Build::DriverInput &SemanticContextLease::driver() const { return data_->plan->driver; } +std::uint64_t SemanticContextLease::configuration_generation() const { + return data_->configuration; +} +std::uint32_t SemanticContextLease::worker_memory_limit_mib() const { + return data_->worker_memory_limit_mib; +} +const std::string &SemanticContextLease::document_uri() const { + return data_->query.document->canonical_uri; +} + +struct WorkspaceSession::State { + struct Install { + std::shared_ptr folder; + std::shared_ptr configuration; + std::uint64_t trust_generation{}; + + void commit() { + if (folder->last_good && !configuration->permits(folder->last_good->source)) + folder->last_good.reset(); + folder->trust_generation = std::max(folder->trust_generation, trust_generation); + folder->config = std::move(configuration); + folder->current_source.reset(); + folder->basis.reset(); + folder->semantic_routes.clear(); + } + }; + + State(WorkspaceLaunch launch, std::function hook) + : launch(std::move(launch)), before_publish(std::move(hook)) { + if (!this->launch.root) + return; + auto root = normalize_directory(*this->launch.root); + if (!root.is_absolute()) { + launch_error = "launcher workspace root must be absolute"; + return; + } + launcher_root = root; + auto layer = parse_settings({}, root); + if (!layer) { + launch_error = layer.error(); + return; + } + const auto merged = merge(*layer); + const auto &settings = merged.effective(); + Build::ProviderScope requested{.workspace = {root, "launcher"}, .limits = settings.limits}; + if (settings.compdb_path) + requested.exact_database = normalize_locator(*settings.compdb_path); + if (settings.vbs_manifest_path) + requested.exact_selector = normalize_locator(*settings.vbs_manifest_path); + if (this->launch.build_root) + requested.build_root = normalize_directory(*this->launch.build_root); + if (this->launch.producer_cwd) + requested.producer_cwd = normalize_directory(*this->launch.producer_cwd); + // This is the sole grant-binding operation for launcher inputs, even if the + // workspace first appears in a later folders notification. + launcher_binding = Build::bind_provider_scope(std::move(requested)); + } + + static fs::path normalize_directory(const fs::path &path) { + auto result = normalize_locator(path); + if (result != result.root_path() && !result.has_filename()) + return result.parent_path(); + return result; + } + + Workspace::MergedConfiguration merge(const Workspace::PartialWorkspaceSettings &layer) const { + if (layer.origin().base != launcher_root) + return Workspace::merge_configuration(layer); + return Workspace::merge_configuration( + layer, launch.user_settings ? &*launch.user_settings : nullptr, + launch.cli_settings ? &*launch.cli_settings : nullptr); + } + + Result> configuration_for(const Address &address, + const ClientSettings &settings) const { + auto values = settings.defaults; + auto overrides = settings.workspaces.find(address.client_key); + if (address.uri != address.client_key) { + if (auto physical = settings.workspaces.find(address.uri); + physical != settings.workspaces.end()) { + if (overrides != settings.workspaces.end()) + return std::unexpected{"multiple settings entries match the same workspace"}; + overrides = physical; + } + } + if (overrides != settings.workspaces.end()) { + for (const auto &[key, value] : overrides->second) + values.insert_or_assign(key, value); + } + auto layer = parse_settings(values, address.root); + if (!layer) + return std::unexpected{layer.error()}; + auto encoded = Protocol::serialize_json(Json{std::move(values)}); + if (!encoded) + return std::unexpected{"could not encode workspace settings"}; + auto merged = merge(*layer); + const auto &effective = merged.effective(); + auto selector = normalize_locator( + effective.vbs_manifest_path.value_or(address.root / ".vbs/editor_selection.json")); + auto database = normalize_locator( + effective.compdb_path.value_or(address.root / "compile_commands.json")); + auto revision = issue_workspace_revision(); + if (!revision) + return std::unexpected{revision.error()}; + return std::make_shared(std::move(*encoded), std::move(merged), + Source{"vbs", std::move(selector)}, + Source{"compdb", std::move(database)}, *revision); + } + + Result make_folder(Address address, const ClientSettings &settings) const { + auto incarnation = issue_workspace_revision(); + if (!incarnation) + return std::unexpected{incarnation.error()}; + auto configuration = configuration_for(address, settings); + if (!configuration) + return std::unexpected{configuration.error()}; + Build::WorkspaceIdentity identity{address.root, std::to_string(*incarnation)}; + Binding binding; + if (launcher_binding && identity.root == launcher_root) { + binding = *launcher_binding + ? Build::reuse_provider_scope(**launcher_binding, identity.session) + : Binding{std::unexpected{launcher_binding->error()}}; + } else { + binding = Build::bind_provider_scope({.workspace = identity}); + if (!binding) + return std::unexpected{"could not bind workspace directory"}; + } + auto folder = + std::make_shared(std::move(address), std::move(identity), std::move(binding)); + return Install{std::move(folder), std::move(*configuration)}; + } + + void prepare_trust(Install &install) { + const auto &root = install.folder->identity.root; + if (install.folder->binding) { + auto updated = trust.replace_configuration(install.configuration->merged); + if (!updated) + install.configuration->trust_error = updated.error(); + } + install.trust_generation = trust.generation(root); + } + + [[nodiscard]] FolderMap snapshot_folders() const { + std::lock_guard lock{mutex}; + return folders; + } + + // TrustPolicy can revoke one changed pin from inside check_tool(). Reconcile while + // holding the owner lock and only for the currently admitted folder incarnation. + void sync_trust(Folder &folder) { + const auto current = trust.generation(folder.identity.root); + if (current > folder.trust_generation) { + folder.trust_generation = current; + folder.current_source.reset(); + folder.basis.reset(); + folder.semantic_routes.clear(); + } + } + + [[nodiscard]] Result> begin(const Query &query) { + std::lock_guard lock{mutex}; + auto match = workspace_for(folders, query); + if (!match) + return std::unexpected{match.error()}; + if (!*match) + return std::nullopt; + auto &folder = **match; + sync_trust(folder); + if (folder.issued == std::numeric_limits::max()) + return std::unexpected{"provider observation limit reached"}; + return Work{*match, folder.config, ++folder.issued, folder.trust_generation, + folder.basis, folder.semantic_issued}; + } + + struct SemanticWork { + Work work; + std::shared_ptr slot; + std::shared_ptr previous; + std::shared_ptr candidate; + }; + + // Selector/status/database authority is shared by all drivers. A failed + // response lookup belongs only to the checked import that observed it. + bool retire_plan(SemanticPlan &plan, const std::shared_ptr &basis, + Evidence evidence) { + if (evidence == Evidence::current) + return false; + plan.retired = true; + if (evidence != Evidence::provider_changed || !basis) + return false; + const auto &workspace = plan.scope.workspace; + auto found = folders.find(workspace.root); + if (found == folders.end() || found->second->identity != workspace || + found->second->basis != basis) + return false; + auto next = *basis; + next.mark_changed(); + replace_basis(*found->second, std::move(next)); + return true; + } + + std::expected begin_semantic(const Query &query, + const SemanticDriver &driver) { + std::lock_guard lock{mutex}; + auto match = workspace_for(folders, query); + if (!match || !*match) + return failure(SemanticContextIssue::unavailable, + match ? "No workspace owns this document" : match.error()); + auto &folder = **match; + sync_trust(folder); + if (folder.identity.root != launcher_root || + folder.config->merged.effective().provider == ProviderPreference::none) + return failure(SemanticContextIssue::disabled, + "Semantic contexts require an opted-in launcher workspace and provider"); + if (!folder.binding) + return failure(SemanticContextIssue::unavailable, folder.binding.error().message); + if (folder.semantic_issued == std::numeric_limits::max()) + return failure(SemanticContextIssue::unavailable, "Semantic observation limit reached"); + const auto key = route_key(query); + auto &routes = folder.semantic_routes; + if (routes.size() == max_semantic_routes && !routes.contains(key)) { + const auto oldest = std::ranges::min_element( + routes, {}, [](const auto &entry) { return entry.second->issued; }); + routes.erase(oldest); + } + auto &slot = routes[key]; + if (!slot || slot->query.document->canonical_path != query.document->canonical_path) + slot = std::make_shared(query); + slot->issued = ++folder.semantic_issued; + + auto reusable = [&](const std::shared_ptr &entry) { + return entry && entry->basis == folder.basis && !entry->plan->retired && + entry->plan->driver.tool.identity.selected_path.native() == + driver.executable.native() && + entry->plan->driver.driver == driver.family; + }; + std::shared_ptr plan; + if (reusable(slot->current)) + plan = slot->current->plan; + else { + for (const auto &[other_key, other] : routes) { + if (reusable(other->current)) { + plan = other->current->plan; + break; + } + } + } + return SemanticWork{ + {*match, folder.config, slot->issued, folder.trust_generation, folder.basis}, + slot, + slot->current, + std::move(plan)}; + } + + // Called under mutex after all filesystem checks. Preserve whether the caller + // requested an explicit folder; adding a nested folder changes the implicit route. + bool current(const Work &work, const Query &query, const std::shared_ptr &slot) { + const auto owner = workspace_for(folders, query); + if (!owner || *owner != work.owner) + return false; + auto &folder = *work.owner; + sync_trust(folder); + const auto active = folder.semantic_routes.find(route_key(query)); + return folder.config == work.config && folder.trust_generation == work.trust_generation && + active != folder.semantic_routes.end() && active->second == slot && + slot->issued == work.sequence; + } + + std::shared_ptr + active_lease(const std::shared_ptr &lease) { + auto route = workspace_for(folders, lease->query); + if (!route || !*route || (*route)->identity != lease->selection->scope->workspace) + return {}; + auto &folder = **route; + sync_trust(folder); + const auto entry = folder.semantic_routes.find(route_key(lease->query)); + if (entry == folder.semantic_routes.end() || entry->second->current != lease || + folder.config->generation != lease->configuration || folder.basis != lease->basis || + folder.trust_generation != lease->plan->driver.tool.trust_generation || + lease->plan->retired) + return {}; + return entry->second; + } + + void expire_ambiguous_routes() { + for (const auto &[root, folder] : folders) { + std::erase_if(folder->semantic_routes, [&](const auto &entry) { + const auto &query = entry.second->query; + if (query.workspace) + return false; + auto owner = workspace_for(folders, query); + return !owner || *owner != folder; + }); + } + } + + WorkspaceLaunch launch; + fs::path launcher_root; + std::optional launcher_binding; + std::optional launch_error; + const std::function before_publish; + std::mutex writers; + bool initialized{}; + ClientSettings client_settings; + Workspace::TrustPolicy trust; + // Scope binding, metadata reads, and configuration parsing happen outside this lock. + mutable std::mutex mutex; + FolderMap folders; +}; + +WorkspaceSession::WorkspaceSession(WorkspaceLaunch launch, std::function before_publish) + : state_(std::make_unique(std::move(launch), std::move(before_publish))) {} + +WorkspaceSession::~WorkspaceSession() = default; + +Result WorkspaceSession::initialize(const Json ¶ms) { + auto &state = *state_; + std::lock_guard writer{state.writers}; + if (state.initialized) + return std::unexpected{"workspace session is already initialized"}; + if (state.launch_error) + return std::unexpected{*state.launch_error}; + const auto *object = as_object(¶ms); + if (!object) + return std::unexpected{"initialize params must be an object"}; + + ClientSettings settings; + if (const auto *options = as_object(find_member(*object, "initializationOptions"))) { + if (const auto *setting = find_member(*options, "voidLanguageServer")) { + auto parsed = read_settings(*setting); + if (!parsed) + return std::unexpected{parsed.error()}; + settings = std::move(*parsed); + } + } + + std::vector keys; + if (const auto *workspaces = find_member(*object, "workspaceFolders")) { + if (!is_null(workspaces)) { + const auto *rows = as_array(workspaces); + if (!rows || rows->size() > max_folders) + return std::unexpected{"workspaceFolders must be a bounded array or null"}; + for (const auto &row : *rows) { + auto key = folder_uri(row); + if (!key) + return std::unexpected{key.error()}; + keys.push_back(std::move(*key)); + } + } + } else if (const auto *legacy = find_member(*object, "rootUri"); legacy && !is_null(legacy)) { + const auto *uri = as_string(legacy); + if (!uri) + return std::unexpected{"rootUri must be a file URI or null"}; + auto key = file_uri_key(*uri); + if (!key) + return std::unexpected{key.error()}; + keys.push_back(std::move(*key)); + } + + FolderMap next; + std::vector added; + for (auto &key : keys) { + auto address = resolve_folder(std::move(key)); + if (!address) + return std::unexpected{address.error()}; + if (!address_available(next, *address)) + return std::unexpected{"duplicate workspace directory"}; + auto install = state.make_folder(std::move(*address), settings); + if (!install) + return std::unexpected{install.error()}; + next.emplace(install->folder->identity.root, install->folder); + added.push_back(std::move(*install)); + } + for (auto &install : added) { + state.prepare_trust(install); + install.commit(); + } + { + std::lock_guard lock{state.mutex}; + state.folders.swap(next); + } + state.client_settings = std::move(settings); + state.initialized = true; + return {}; +} + +Result WorkspaceSession::update_folders(const Json *params) { + auto &state = *state_; + std::lock_guard writer{state.writers}; + if (!state.initialized) + return std::unexpected{"workspace session is not initialized"}; + const auto *object = as_object(params); + const auto *event = object ? as_object(find_member(*object, "event")) : nullptr; + const auto *added = event ? as_array(find_member(*event, "added")) : nullptr; + const auto *removed = event ? as_array(find_member(*event, "removed")) : nullptr; + if (!added || !removed || added->size() > max_folders || removed->size() > max_folders) + return std::unexpected{"workspace folder change requires bounded added and removed arrays"}; + + auto next = state.snapshot_folders(); + std::vector removed_roots; + for (const auto &folder : *removed) { + auto key = folder_uri(folder); + if (!key) + return std::unexpected{key.error()}; + const auto match = find_folder(next, *key); + if (match == next.end()) + return std::unexpected{"removed workspace folder is not active"}; + removed_roots.push_back(match->first); + next.erase(match); + } + if (next.size() + added->size() > max_folders) + return std::unexpected{"workspace folder limit reached"}; + std::vector installs; + for (const auto &folder : *added) { + auto key = folder_uri(folder); + if (!key) + return std::unexpected{key.error()}; + auto address = resolve_folder(std::move(*key)); + if (!address) + return std::unexpected{address.error()}; + if (!address_available(next, *address)) + return std::unexpected{"duplicate workspace directory"}; + auto install = state.make_folder(std::move(*address), state.client_settings); + if (!install) + return std::unexpected{install.error()}; + next.emplace(install->folder->identity.root, install->folder); + installs.push_back(std::move(*install)); + } + + for (const auto &root : removed_roots) + state.trust.revoke_root_authority(root); + for (auto &install : installs) { + state.prepare_trust(install); + install.commit(); + } + { + std::lock_guard lock{state.mutex}; + state.folders.swap(next); + state.expire_ambiguous_routes(); + } + return {}; +} + +Result WorkspaceSession::configure(const Json *params) { + auto &state = *state_; + std::lock_guard writer{state.writers}; + if (!state.initialized) + return std::unexpected{"workspace session is not initialized"}; + const auto *object = as_object(params); + const auto *settings = object ? find_member(*object, "settings") : nullptr; + const auto *settings_object = as_object(settings); + if (is_null(settings)) + return {}; + if (!settings_object) + return std::unexpected{"configuration change requires a settings object"}; + const auto *payload = find_member(*settings_object, "voidLanguageServer"); + if (!payload) + return {}; + auto parsed = read_settings(*payload); + if (!parsed) + return std::unexpected{parsed.error()}; + + std::vector installs; + for (const auto &[root, folder] : state.snapshot_folders()) { + auto configuration = state.configuration_for(folder->address, *parsed); + if (!configuration) + return std::unexpected{configuration.error()}; + if ((*configuration)->client_values != folder->config->client_values) + installs.push_back({folder, std::move(*configuration)}); + } + for (auto &install : installs) + state.prepare_trust(install); + { + std::lock_guard lock{state.mutex}; + for (auto &install : installs) + install.commit(); + } + state.client_settings = std::move(*parsed); + return {}; +} + +void WorkspaceSession::revoke_root_authority(const fs::path &root) { + auto &state = *state_; + std::lock_guard writer{state.writers}; + state.trust.revoke_root_authority(root); + const auto trust_generation = state.trust.generation(root); + std::lock_guard lock{state.mutex}; + if (const auto active = state.folders.find(root); active != state.folders.end()) { + auto &folder = *active->second; + folder.trust_generation = trust_generation; + folder.current_source.reset(); + folder.basis.reset(); + folder.semantic_routes.clear(); + if (folder.issued != std::numeric_limits::max()) + ++folder.issued; + else + folder.config = std::make_shared(*folder.config); + } +} + +Result WorkspaceSession::provider_status(const Json *params) { + auto query = read_query(params); + if (!query) + return std::unexpected{query.error()}; + auto ticket = state_->begin(*query); + if (!ticket) + return std::unexpected{ticket.error()}; + if (!*ticket) + return document_only(*query); + auto &work = **ticket; + + auto scope = work.scope(); + auto observed = observe(work, scope ? &*scope : nullptr); + // Bind the queried spelling along with its compilation row. The editor may + // have reached the same file through a different link from the database. + const auto original_path = query->document ? query->document->canonical_path : fs::path{}; + Build::ProviderObservation binding; + if (scope && query->document && !original_path.empty()) { + const auto &lookup_path = below(query->document_spelling, scope->workspace.root) + ? query->document_spelling + : original_path; + auto lookup = + Build::inspect_command_path(*scope, lookup_path, Build::CommandPathKind::file); + if (lookup.physical_path != original_path) + query->document->canonical_path.clear(); + binding.lookups.paths.push_back(std::move(lookup)); + } + if (state_->before_publish) + state_->before_publish(); + + const bool document_current = [&] { + if (!query->document || !query->document->is_file_uri) + return true; + auto latest = Docs::normalize_uri(query->document->display_uri); + return latest && latest->canonical_path == original_path && + (!scope || !Build::changed_provider_input(*scope, binding)); + }(); + const bool provider_current = !scope || check_evidence(*scope, observed) == Evidence::current; + const bool stable = document_current && provider_current; + const bool previous_current = basis_current(work, scope ? &*scope : nullptr); + ProviderBasis basis{observed}; + if (!provider_current) + basis.mark_changed(); + auto fields = generation_fields(observed.result); + std::shared_ptr incoming; + if (stable && observed.result.health == ProviderHealth::ready && observed.result.generation) + incoming = std::make_shared(observed.source, fields); + + std::shared_ptr last_good; + bool latest = false; + { + std::lock_guard lock{state_->mutex}; + const auto found = state_->folders.find(work.owner->identity.root); + if (found != state_->folders.end() && found->second == work.owner) { + auto &folder = *work.owner; + state_->sync_trust(folder); + latest = folder.issued == work.sequence && folder.config == work.config && + folder.trust_generation == work.trust_generation; + if (latest) + latest = install_basis(work, basis, previous_current); + if (latest && query->document) { + for (const bool explicit_workspace : {false, true}) { + const auto slot = + folder.semantic_routes.find({query->document_spelling, explicit_workspace}); + if (slot == folder.semantic_routes.end() || + slot->second->issued > work.semantic_cutoff) + continue; + const auto &physical = slot->second->query.document->canonical_path; + if ((document_current && physical != query->document->canonical_path) || + (!document_current && physical == original_path)) + folder.semantic_routes.erase(slot); + } + } + if (latest && stable) { + folder.current_source = observed.source; + if (incoming) + folder.last_good = std::move(incoming); + else if (folder.last_good && folder.last_good->source != observed.source) + folder.last_good.reset(); + } else { + work.config = folder.config; + if (!latest && folder.current_source) + observed.source = *folder.current_source; + } + last_good = folder.last_good; + } + } + if (!latest || !stable) { + observed.result = { + .provider = std::string{observed.source.provider}, + .health = ProviderHealth::changed, + .issues = { + latest ? Build::ProviderIssue{"inputs_changed", + "Metadata changed during observation", + {}} + : Build::ProviderIssue{"superseded", + "A newer workspace state superseded this observation", + {}}}}; + fields = generation_fields(observed.result); + } + return workspace_status(work, observed, *query, last_good, std::move(fields)); +} + +std::expected +WorkspaceSession::acquire_semantic_context(std::string_view document_uri, + std::optional workspace_uri, + const SemanticDriver &selected_driver) { + using enum SemanticContextIssue; + Query query; + if (auto parsed = set_document(query, document_uri); !parsed) + return failure(unavailable, parsed.error()); + if (!query.document->is_file_uri || query.document->canonical_path.empty()) + return failure(no_command, "The document has no physical workspace path"); + if (workspace_uri) { + auto key = file_uri_key(*workspace_uri); + if (!key) + return failure(unavailable, key.error()); + query.workspace = std::move(*key); + } + auto &state = *state_; + auto started = state.begin_semantic(query, selected_driver); + if (!started) + return std::unexpected{std::move(started.error())}; + auto &[work, slot, previous, candidate] = *started; + const auto &root = work.owner->identity.root; + const auto purpose = Workspace::AuthorityLevel::compiler_use; + auto fail = [&](SemanticContextIssue issue, std::string message) { + std::lock_guard lock{state.mutex}; + if (!state.current(work, query, slot)) + return failure(SemanticContextIssue::superseded, std::move(message)); + slot->current.reset(); + return failure(issue, std::move(message)); + }; + if (!selected_driver.executable.is_absolute() || + (selected_driver.family != Workspace::CompilerDriver::gcc && + selected_driver.family != Workspace::CompilerDriver::clang)) + return fail(wrong_command, "Select an absolute GCC or Clang launcher driver"); + auto check = [&] { + return state.trust.check_tool(root, purpose, selected_driver.executable, + work.trust_generation); + }; + auto plan = candidate; + if (plan) { + const auto cached = check_evidence(plan->scope, plan->observed); + if (cached != Evidence::current) { + std::lock_guard lock{state.mutex}; + if (!state.current(work, query, slot)) + return vls::superseded(); + if (state.retire_plan(*plan, work.basis, cached)) + work.basis = work.owner->basis; + plan.reset(); + } + } + if (!plan) { + auto checked = check(); + if (!checked && checked.error() == Workspace::TrustError::tool_not_pinned) + checked = state.trust.pin_approved_tool(root, purpose, selected_driver.executable); + if (!checked) + return fail(unavailable, std::string{Workspace::trust_error_message(checked.error())}); + if (checked->trust_generation != work.trust_generation) + return fail(SemanticContextIssue::superseded, "The launcher driver authority changed"); + auto scope = *work.scope(); + Build::DriverInput driver{std::move(*checked), selected_driver.family, + work.config->merged.effective().approved_wrappers}; + auto observed = observe(work, &scope, driver); + plan = std::make_shared(std::move(scope), std::move(driver), + std::move(observed)); + } + auto lookup = document_binding(query, *work.owner, plan->scope); + const bool bound = lookup.physical_path == query.document->canonical_path; + Build::ProviderObservation binding; + binding.lookups.paths.push_back(std::move(lookup)); + if (state.before_publish) + state.before_publish(); + + const auto checked = check(); + if (!checked) + return fail(unavailable, std::string{Workspace::trust_error_message(checked.error())}); + const auto &observed = plan->observed; + const auto evidence = check_evidence(plan->scope, observed); + const bool same_document = document_current(query, plan->scope, binding); + const bool same_previous_document = + previous && previous->plan == plan && + document_current(previous->query, plan->scope, previous->document_binding); + const bool previous_basis_current = basis_current(work, &plan->scope); + const ProviderBasis basis{observed}; + std::lock_guard lock{state.mutex}; + if (!state.current(work, query, slot)) + return vls::superseded(); + state.retire_plan(*plan, work.basis, evidence); + if (plan->retired || !same_document || !install_basis(work, basis, previous_basis_current)) { + slot->current.reset(); + return vls::superseded(); + } + if (bound && same_previous_document && slot->current == previous) + return SemanticContextLease{previous}; + + slot->current.reset(); + const auto &result = observed.result; + if (result.health != ProviderHealth::ready || !result.generation) { + const auto &issues = result.issues; + return failure(unavailable, issues.empty() ? "The provider has no current generation" + : issues.front().message); + } + if (!bound) + return failure(no_command, "The requested document route is outside the workspace binding"); + // A rejected driver must not advance another route's per-file selection state. + // Select from every candidate first, including rows this driver could not import. + auto trial = std::make_shared(work.owner->identity, + query.document->canonical_path); + const auto &profile = work.config->merged.effective().selected_profile; + auto selection = select_context(*trial, result.generation, profile); + if (!selection) + return failure(unavailable, "Could not select the workspace build context"); + const auto *context = (*selection)->selected; + if (!context) + return failure(no_command, "No compilation command owns this document"); + if (!context->semantic_arguments || !context->original || !context->working_directory) + return failure(wrong_command, context->limitations.empty() + ? "The selected row has no checked invocation" + : context->limitations.front()); + + if (!slot->selector) { + for (const auto &[key, other] : work.owner->semantic_routes) { + if (other->selector && + other->selector->scope()->file == query.document->canonical_path) { + slot->selector = other->selector; + break; + } + } + } + if (slot->selector) { + selection = select_context(*slot->selector, result.generation, profile); + if (!selection) + return failure(unavailable, "The build selection revision limit was reached"); + } else { + slot->selector = std::move(trial); + } + slot->current = std::make_shared( + std::move(query), std::move(binding), work.owner->basis, std::move(plan), slot->selector, + std::move(*selection), work.config->generation, + work.config->merged.effective().limits.worker_memory_limit_mib); + return SemanticContextLease{slot->current}; +} + +std::expected +WorkspaceSession::validate_semantic_context(const SemanticContextLease &lease) { + const auto &data = lease.data_; + auto &state = *state_; + { + std::lock_guard lock{state.mutex}; + if (!data || !state.active_lease(data)) + return superseded(); + } + if (state.before_publish) + state.before_publish(); + const auto &plan = *data->plan; + const auto &tool = plan.driver.tool; + auto checked = state.trust.check_tool(tool.workspace_root, tool.operation, + tool.identity.selected_path, tool.trust_generation); + const auto evidence = checked ? check_evidence(plan.scope, plan.observed) : Evidence::current; + const bool same_document = + checked && document_current(data->query, plan.scope, data->document_binding); + std::lock_guard lock{state.mutex}; + auto slot = state.active_lease(data); + if (!checked) + return failure(SemanticContextIssue::superseded, + std::string{Workspace::trust_error_message(checked.error())}); + if (!slot) + return superseded(); + state.retire_plan(*data->plan, data->basis, evidence); + if (evidence != Evidence::current || !same_document || checked->identity != tool.identity) { + slot->current.reset(); + return superseded(); + } + return {}; +} + +} // namespace vls diff --git a/src/debug/Fields.hpp b/src/debug/Fields.hpp new file mode 100644 index 0000000..fd2b7b7 --- /dev/null +++ b/src/debug/Fields.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include + +namespace vls::debug { +namespace Protocol = Void::LanguageServer::Protocol; +using Json = Protocol::Json; + +inline Json text(std::string_view value) { return Json{std::string(value)}; } +inline Json number(std::int64_t value) { return Json{value}; } + +inline std::optional integer(const Json::Object &object, std::string_view key) { + const auto *member = Protocol::find_member(object, key); + if (member) + if (const auto *value = std::get_if(&member->value)) + return *value; + return {}; +} + +inline std::optional string_field(const Json::Object &object, + std::string_view key) { + if (const auto *value = Protocol::as_string(Protocol::find_member(object, key))) + return *value; + return {}; +} +} // namespace vls::debug diff --git a/src/debug/dap/Main.cpp b/src/debug/dap/Main.cpp new file mode 100644 index 0000000..35baf21 --- /dev/null +++ b/src/debug/dap/Main.cpp @@ -0,0 +1,681 @@ +#include "../Fields.hpp" +#include "Projection.hpp" + +#include +#include + +#include + +#include +#include +#include +#include + +namespace vls::debug::dap { +namespace { +constexpr auto max_seq = std::numeric_limits::max(); +struct Request { + std::int64_t seq; + std::string command; +}; + +struct LiveLaunch { + std::filesystem::path worker, compiler, source, trace; + std::string sha256; +}; + +std::vector splice_origins(const Json::Object &snapshot) { + std::vector origins; + const auto *list = Protocol::as_array(Protocol::find_member(snapshot, "origins")); + if (!list) + return origins; + for (const auto &item : *list) { + const auto *fields = Protocol::as_object(&item); + if (!fields) + continue; + reflection::SpliceOrigin origin; + origin.source = string_field(*fields, "source").value_or(""); + origin.line = static_cast(integer(*fields, "line").value_or(0)); + origin.byteColumn = static_cast(integer(*fields, "byteColumn").value_or(0)); + origin.targetKind = string_field(*fields, "targetKind").value_or(""); + origin.targetName = string_field(*fields, "targetName").value_or(""); + origin.targetSource = string_field(*fields, "targetSource").value_or(""); + if (const auto line = integer(*fields, "targetLine")) + origin.targetLine = static_cast(*line); + if (const auto column = integer(*fields, "targetByteColumn")) + origin.targetByteColumn = static_cast(*column); + origins.push_back(std::move(origin)); + } + return origins; +} + +class Adapter { + public: + explicit Adapter(std::filesystem::path trace, std::optional live = {}) + : selected_(std::move(trace)), live_launch_(std::move(live)) {} + void run(std::istream &input, std::ostream &output); + + private: + std::filesystem::path selected_; + std::optional live_launch_; + std::optional live_; + std::map> live_breakpoints_; + std::uint64_t live_generation_{}; + std::ostream *output_{}; + std::optional session_; + std::optional launch_; + std::int64_t received_{}, sent_{}; + bool initialized_{}, configured_{}, ended_{}, disconnected_{}; + bool variable_paging_{}; + + void begin_live(); + void live_stop_event(); + void live_breakpoints(const Request &, const Json::Object &); + void move_live(const Request &, bool step); + [[nodiscard]] Json inspect_live(); + [[nodiscard]] std::int64_t live_handle(std::size_t frame) const; + [[nodiscard]] std::size_t live_frame(std::int64_t handle) const; + void live_stack(const Request &, const Json::Object &); + void live_scopes(const Request &, const Json::Object &); + void live_variables(const Request &, const Json::Object &); + + void write(Json::Object); + void response(const Request &, Json::Object body = {}); + void failure(const Request &, std::string_view message); + void event(std::string_view name, Json::Object body = {}); + void position_event(); + void finish(); + void begin_if_ready(); + void end_pending_launch(std::string_view reason); + [[noreturn]] void invalid_input(std::string_view reason); + void dispatch(const Request &, const Json::Object &arguments); +}; + +void Adapter::write(Json::Object message) { + if (sent_ == max_seq) + throw std::runtime_error("DAP output sequence exhausted"); + message.emplace("seq", number(++sent_)); + auto result = Protocol::write_json_frame(*output_, Json{std::move(message)}); + if (!result) + throw std::runtime_error(result.error()); +} +void Adapter::response(const Request &r, Json::Object body) { + write({{"type", text("response")}, + {"request_seq", number(r.seq)}, + {"command", text(r.command)}, + {"success", Json{true}}, + {"body", Json{std::move(body)}}}); +} +void Adapter::failure(const Request &r, std::string_view message) { + write({{"type", text("response")}, + {"request_seq", number(r.seq)}, + {"command", text(r.command)}, + {"success", Json{false}}, + {"message", text(message)}}); +} +void Adapter::event(std::string_view name, Json::Object body) { + write({{"type", text("event")}, {"event", text(name)}, {"body", Json{std::move(body)}}}); +} +void Adapter::position_event() { + if (live_) { + live_stop_event(); + return; + } + const auto kind = session_->pause_kind(); + const auto description = kind == "recordedStop" ? "Recorded compiler stop" + : kind == "value" ? "Recorded evaluation result" + : "Recorded compiler event"; + event("stopped", {{"reason", text(kind)}, + {"description", text(description)}, + {"threadId", number(1)}, + {"allThreadsStopped", Json{true}}}); +} +void Adapter::finish() { + if (ended_) + return; + ended_ = true; + if (session_) + session_->finish(); + event("terminated"); +} +void Adapter::begin_if_ready() { + if (!launch_ || !configured_) + return; + const auto request = std::move(*launch_); + launch_.reset(); + auto moved = session_->initial_position(); + if (!moved) { + failure(request, moved.error()); + finish(); + return; + } + response(request); + if (*moved) + position_event(); + else + finish(); +} + +void Adapter::begin_live() { + if (!launch_ || !live_ || !configured_) + return; + auto request = std::move(*launch_); + launch_.reset(); + auto started = live_->start(); + if (!started) { + failure(request, started.error()); + finish(); + return; + } + response(request); + live_generation_ = started->generation; + position_event(); +} + +void Adapter::live_stop_event() { + Json::Object body{{"reason", text("step")}, + {"description", text("Private compiler stop")}, + {"threadId", number(1)}, + {"allThreadsStopped", Json{true}}}; + std::vector hits; + const auto snapshot = live_->inspect(); + if (snapshot) { + const auto *fields = Protocol::as_object(&*snapshot); + const auto *frames = + fields ? Protocol::as_array(Protocol::find_member(*fields, "frames")) : nullptr; + const auto *frame = + frames && !frames->empty() ? Protocol::as_object(&frames->front()) : nullptr; + const auto line = frame ? integer(*frame, "line") : std::nullopt; + const auto source = frame ? string_field(*frame, "source") : std::nullopt; + if (line && source) { + const auto selected = live_breakpoints_.find(std::string{*source}); + if (selected != live_breakpoints_.end() && + std::ranges::contains(selected->second, *line)) + hits.push_back(*line); + } + } + if (!hits.empty()) { + Json::Array ids; + for (const auto hit : hits) + ids.push_back(number(hit)); + body.insert_or_assign("reason", text("breakpoint")); + body.emplace("hitBreakpointIds", Json{std::move(ids)}); + } + event("stopped", std::move(body)); +} + +void Adapter::live_breakpoints(const Request &r, const Json::Object &args) { + const auto *source = Protocol::find_member(args, "source"); + const auto *source_fields = source ? Protocol::as_object(source) : nullptr; + const auto path = source_fields ? string_field(*source_fields, "path") : std::nullopt; + if (!path) + throw RequestError("breakpoints require a source path"); + const auto *lines = Protocol::as_array(Protocol::find_member(args, "lines")); + if (!lines || lines->size() > 4096) + throw RequestError("invalid breakpoint list"); + std::vector selected; + Json::Array returned; + for (const auto &entry : *lines) { + const auto *line = std::get_if(&entry.value); + if (!line || *line < 0) + throw RequestError("invalid breakpoint line"); + selected.push_back(*line); + returned.push_back(Json{Json::Object{{"verified", Json{true}}, {"line", number(*line)}}}); + } + live_breakpoints_[std::string{*path}] = std::move(selected); + response(r, {{"breakpoints", Json{std::move(returned)}}}); +} + +void Adapter::move_live(const Request &r, bool step) { + auto moved = step ? live_->step() : live_->continue_run(); + if (!moved) + throw RequestError(moved.error()); + if (step) + response(r); + else + response(r, {{"allThreadsContinued", Json{true}}}); + if (*moved) { + live_generation_ = (*moved)->generation; + position_event(); + } else { + finish(); + } +} + +Json Adapter::inspect_live() { + auto snapshot = live_->inspect(); + if (!snapshot) + throw RequestError(snapshot.error()); + return std::move(*snapshot); +} + +std::int64_t Adapter::live_handle(std::size_t frame) const { + return static_cast(live_generation_ * 1000 + frame + 1); +} + +std::size_t Adapter::live_frame(std::int64_t handle) const { + if (handle <= 0) + throw RequestError("invalid live frame handle"); + const auto generation = static_cast(handle) / 1000; + const auto index = static_cast(handle) % 1000; + if (generation != live_generation_ || index == 0) + throw RequestError("stale live frame handle"); + return static_cast(index - 1); +} + +void Adapter::live_stack(const Request &r, const Json::Object &args) { + if (argument_number(args, "threadId") != 1) + throw RequestError("unknown live thread"); + const auto snapshot = inspect_live(); + const auto *snapshot_fields = Protocol::as_object(&snapshot); + const auto *frames = snapshot_fields + ? Protocol::as_array(Protocol::find_member(*snapshot_fields, "frames")) + : nullptr; + if (!frames || frames->size() > 256) + throw RequestError("invalid live frame list"); + Json::Array stack; + for (std::size_t index = 0; index != frames->size(); ++index) { + const auto *fields = Protocol::as_object(&(*frames)[index]); + if (!fields) + throw RequestError("invalid live frame"); + Json::Object frame; + frame.emplace("id", number(live_handle(index))); + frame.emplace("name", text(string_field(*fields, "name").value_or(""))); + if (const auto line = integer(*fields, "line")) + frame.emplace("line", number(*line)); + if (const auto source = string_field(*fields, "source")) + frame.emplace("source", Json{Json::Object{{"name", text(*source)}}}); + stack.push_back(Json{std::move(frame)}); + } + response(r, {{"stackFrames", Json{std::move(stack)}}, + {"totalFrames", number(static_cast(frames->size()))}}); +} + +void Adapter::live_scopes(const Request &r, const Json::Object &args) { + const auto frame = argument_number(args, "frameId"); + static_cast(live_frame(frame)); + Json::Array scopes; + scopes.push_back(Json{Json::Object{{"name", text("Compiler state")}, + {"variablesReference", number(frame)}, + {"expensive", Json{false}}}}); + response(r, {{"scopes", Json{std::move(scopes)}}}); +} + +void Adapter::live_variables(const Request &r, const Json::Object &args) { + const auto handle = argument_number(args, "variablesReference"); + const auto index = live_frame(handle); + const auto snapshot = inspect_live(); + const auto *snapshot_fields = Protocol::as_object(&snapshot); + const auto *frames = snapshot_fields + ? Protocol::as_array(Protocol::find_member(*snapshot_fields, "frames")) + : nullptr; + if (!frames || index >= frames->size()) + throw RequestError("unknown live frame"); + const auto *fields = Protocol::as_object(&(*frames)[index]); + if (!fields) + throw RequestError("invalid live frame"); + Json::Array variables; + for (const auto &[name, value] : *fields) { + if (variables.size() == 64) + break; + std::string rendered; + if (const auto *string = Protocol::as_string(&value)) + rendered = *string; + else if (const auto *number_value = std::get_if(&value.value)) + rendered = std::to_string(*number_value); + else if (const auto flag = Protocol::as_bool(&value)) + rendered = *flag ? "true" : "false"; + else if (auto encoded = Protocol::serialize_json(value)) + rendered = encoded->substr(0, 4096); + else + continue; + if (rendered.size() > 4096) + rendered.resize(4096); + variables.push_back(Json{Json::Object{ + {"name", text(name)}, {"value", text(rendered)}, {"variablesReference", number(0)}}}); + } + if (const auto *values = Protocol::as_array(Protocol::find_member(*snapshot_fields, "values"))) + for (const auto &item : *values) { + if (variables.size() == 64) + break; + const auto *typed = Protocol::as_object(&item); + if (!typed) + continue; + const auto name = string_field(*typed, "name").value_or("value"); + const auto rendered = string_field(*typed, "value").value_or(""); + variables.push_back(Json{Json::Object{{"name", text(name)}, + {"value", text(rendered)}, + {"variablesReference", number(0)}}}); + } + // Compiler-reported splice origins become read-only reflected-entity + // entries with their provenance chain, never editable text. + const auto origins = splice_origins(*snapshot_fields); + if (!origins.empty()) { + const auto reflected = reflection::snapshot_from_splices(origins); + for (const auto &entity : reflected.entities()) { + if (variables.size() == 64) + break; + const reflection::Origin *declaration{}; + const reflection::Origin *splice{}; + for (const auto &origin : entity.provenance.origins) { + if (!origin.range) + continue; + if (origin.kind == reflection::OriginKind::reflected_declaration && !declaration) + declaration = &origin; + if (origin.kind == reflection::OriginKind::splice && !splice) + splice = &origin; + } + std::string rendered = "reflected " + entity.name; + const auto append = [&rendered](std::string_view prefix, + const reflection::Range &range) { + rendered += std::string{prefix} + range.path + ":" + std::to_string(range.line) + + ":" + std::to_string(range.character); + }; + if (declaration) + append(" at ", *declaration->range); + if (splice) { + append(" (splice at ", *splice->range); + rendered += ")"; + } + variables.push_back(Json{Json::Object{{"name", text(entity.name)}, + {"value", text(rendered)}, + {"variablesReference", number(0)}}}); + } + } + response(r, {{"variables", Json{std::move(variables)}}}); +} + +void Adapter::end_pending_launch(std::string_view reason) { + if (!launch_) + return; + const auto pending = std::move(*launch_); + launch_.reset(); + failure(pending, reason); +} + +void Adapter::invalid_input(std::string_view reason) { + end_pending_launch(reason); + throw std::runtime_error(std::string(reason)); +} + +Json::Object source_breakpoints(const Json::Object &args) { + if (!Protocol::as_object(Protocol::find_member(args, "source"))) + throw RequestError("source breakpoints require a source"); + const auto name = args.contains("breakpoints") ? "breakpoints" : "lines"; + const auto *requested = Protocol::find_member(args, name); + Json::Array result; + if (requested) { + const auto *entries = Protocol::as_array(requested); + if (!entries || entries->size() > 4096) + throw RequestError("invalid breakpoint list"); + for (const auto &entry : *entries) { + constexpr std::int64_t max_coordinate = 9007199254740991; + if (args.contains("breakpoints")) { + const auto *bp = Protocol::as_object(&entry); + if (!bp) + throw RequestError("invalid source breakpoint"); + argument_number(*bp, "line", max_coordinate); + if (bp->contains("column")) + argument_number(*bp, "column", max_coordinate); + } else { + const auto *line = std::get_if(&entry.value); + if (!line || *line < 0 || *line > max_coordinate) + throw RequestError("invalid breakpoint line"); + } + result.push_back(Json{Json::Object{ + {"verified", Json{false}}, + {"message", text("The recording has no executable source breakpoint locations")}}}); + } + } + return {{"breakpoints", Json{std::move(result)}}}; +} + +void Adapter::dispatch(const Request &r, const Json::Object &args) { + if (r.command == "initialize") { + if (initialized_) + throw RequestError("adapter is already initialized"); + if (!string_field(args, "adapterID")) + throw RequestError("initialize requires adapterID"); + if (const auto *paging = Protocol::find_member(args, "supportsVariablePaging")) { + const auto supported = Protocol::as_bool(paging); + if (!supported) + throw RequestError("supportsVariablePaging must be a boolean"); + variable_paging_ = *supported; + } + initialized_ = true; + response(r, {{"supportsConfigurationDoneRequest", Json{true}}, + {"supportsTerminateRequest", Json{true}}, + {"supportsLoadedSourcesRequest", Json{true}}, + {"supportsDelayedStackTraceLoading", Json{true}}}); + event("initialized"); + return; + } + if (!initialized_) + throw RequestError("initialize the adapter first"); + if (r.command == "disconnect" || r.command == "terminate") { + end_pending_launch("launch ended before configuration completed"); + if (live_) + static_cast(live_->cancel()); + response(r); + finish(); + disconnected_ = r.command == "disconnect"; + return; + } + if (r.command == "launch") { + if (live_launch_) { + if (live_ || ended_) + throw RequestError("this adapter accepts one live session"); + live_.emplace(live::Options{live_launch_->worker, live_launch_->compiler, + live_launch_->sha256, live_launch_->source, + live_launch_->trace, true}); + launch_ = r; + return; + } + if (session_ || ended_) + throw RequestError("this adapter accepts one recording"); + if (args.contains("noDebug") && + Protocol::as_bool(Protocol::find_member(args, "noDebug")) != false) + throw RequestError("replay requires a debug launch"); + if (args.contains("trace") && string_field(args, "trace") != selected_.native()) + throw RequestError("launch trace differs from the recording selected by the launcher"); + auto opened = ReplaySession::open(selected_); + if (!opened) + throw RequestError(opened.error()); + session_.emplace(std::move(*opened)); + launch_ = r; + begin_if_ready(); + return; + } + if (r.command == "configurationDone") { + if (configured_ || ended_) + throw RequestError("configuration is closed"); + configured_ = true; + response(r); + if (live_) + begin_live(); + else + begin_if_ready(); + return; + } + if (r.command == "setBreakpoints" && !ended_ && !live_) { + response(r, source_breakpoints(args)); + return; + } + if (r.command == "setExceptionBreakpoints" && !ended_) { + for (const auto *key : {"filters", "filterOptions", "exceptionOptions"}) { + const auto *field = Protocol::find_member(args, key); + if (!field && std::string_view(key) != "filters") + continue; + const auto *list = Protocol::as_array(field); + if (!list || !list->empty()) + throw RequestError( + "no exception breakpoint filters are available in this recording"); + } + response(r, {{"breakpoints", Json{Json::Array{}}}}); + return; + } + if (live_) { + if (r.command == "setBreakpoints") { + live_breakpoints(r, args); + return; + } + if (r.command == "continue" || r.command == "next") { + move_live(r, r.command == "next"); + return; + } + if (r.command == "threads") { + Json::Array threads; + threads.push_back( + Json{Json::Object{{"id", number(1)}, {"name", text("Private GCC worker")}}}); + response(r, {{"threads", Json{std::move(threads)}}}); + return; + } + if (r.command == "stackTrace") { + live_stack(r, args); + return; + } + if (r.command == "scopes") { + live_scopes(r, args); + return; + } + if (r.command == "variables") { + live_variables(r, args); + return; + } + if (r.command == "pause" || r.command == "stepIn" || r.command == "stepOut") + throw RequestError("the private worker supports only next and continue"); + throw RequestError("unsupported live request"); + } + if (!session_ || !configured_) + throw RequestError("no configured replay session"); + if (r.command == "continue" || r.command == "vls/seek") { + if (ended_ || !session_->paused()) + throw RequestError("no active replay cursor"); + if (r.command == "continue") { + if (argument_number(args, "threadId") != 1) + throw RequestError("unknown replay thread"); + if (const auto *context = Protocol::find_member(args, "vlsContext")) { + const auto *fields = Protocol::as_object(context); + if (!fields || !session_->matches(*fields)) + throw RequestError("stale or incompatible replay context"); + } + auto moved = session_->move_to_value(true); + if (!moved) + throw RequestError(moved.error()); + response(r, {{"allThreadsContinued", Json{true}}}); + if (!*moved) { + finish(); + return; + } + } else { + if (!session_->matches(args)) + throw RequestError("stale or incompatible inspection context"); + if (args.contains("eventSequence") == args.contains("direction")) + throw RequestError("select one event or value direction"); + if (args.contains("eventSequence")) { + auto moved = session_->seek( + static_cast(argument_number(args, "eventSequence"))); + if (!moved) + throw RequestError(moved.error()); + } else { + const auto direction = string_field(args, "direction"); + if (direction != "nextValue" && direction != "previousValue") + throw RequestError("unknown seek direction"); + auto moved = session_->move_to_value(direction == "nextValue"); + if (!moved) + throw RequestError(moved.error()); + if (!*moved) + throw RequestError("no recorded value in that direction"); + } + response(r, session_->describe()); + } + position_event(); + return; + } + response(r, inspect(r.command, args, *session_, variable_paging_)); +} + +void Adapter::run(std::istream &input, std::ostream &output) { + output_ = &output; + while (!disconnected_) { + auto frame = Protocol::read_frame(input, {.body_bytes = 1024 * 1024}); + if (!frame) + invalid_input(frame.error()); + if (!*frame) { + end_pending_launch("input closed before configuration completed"); + return; + } + auto decoded = Protocol::parse_json(**frame); + const auto *fields = decoded ? Protocol::as_object(&*decoded) : nullptr; + if (!fields) + invalid_input("invalid DAP message"); + if (string_field(*fields, "type") != "request") + invalid_input("expected a DAP request"); + const auto seq = integer(*fields, "seq"); + const auto command = string_field(*fields, "command"); + if (!seq || *seq < 1 || *seq > max_seq || !command || command->empty() || + command->size() > 256) + invalid_input("uncorrelatable DAP request"); + const Request request{*seq, std::string(*command)}; + if (*seq != received_ + 1) { + // A repeated sequence cannot identify a new request. Never emit two + // responses for the same correlation, even while launch is deferred. + if (*seq > received_) + failure(request, "out-of-order request sequence"); + invalid_input("out-of-order DAP request sequence"); + } + received_ = *seq; + try { + const auto *arguments = Protocol::find_member(*fields, "arguments"); + const auto *args = Protocol::as_object(arguments); + if (arguments && !args) + throw RequestError("arguments must be an object"); + static const Json::Object empty; + dispatch(request, args ? *args : empty); + } catch (const RequestError &err) { + failure(request, err.what()); + } + } +} +} // namespace +} // namespace vls::debug::dap + +int main(int argc, char **argv) { + if (argc == 2 && std::string_view(argv[1]) == "--help") { + std::cout << "Usage: vls-dap --replay ABSOLUTE_TRACE\n" + " vls-dap --live WORKER COMPILER SHA256 SOURCE TRACE\n"; + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--version") { + std::cout << "vls-dap 0.1.0\n"; + return 0; + } + std::optional live; + if (argc == 7 && std::string_view(argv[1]) == "--live") { + const std::string sha{argv[4]}; + if (sha.size() != 64 || sha.find_first_not_of("0123456789abcdef") != std::string::npos || + !std::filesystem::path(argv[2]).is_absolute() || + !std::filesystem::path(argv[3]).is_absolute() || + !std::filesystem::path(argv[5]).is_absolute() || + !std::filesystem::path(argv[6]).is_absolute()) { + std::cerr << "Usage: vls-dap --live WORKER COMPILER SHA256 SOURCE TRACE\n"; + return 2; + } + live = vls::debug::dap::LiveLaunch{argv[2], argv[3], argv[5], argv[6], sha}; + } else if (argc != 3 || std::string_view(argv[1]) != "--replay" || + !std::filesystem::path(argv[2]).is_absolute()) { + std::cerr << "Usage: vls-dap --replay ABSOLUTE_TRACE\n"; + return 2; + } + std::signal(SIGPIPE, SIG_IGN); + try { + vls::debug::dap::Adapter(argc == 7 ? std::filesystem::path{argv[6]} + : std::filesystem::path{argv[2]}, + std::move(live)) + .run(std::cin, std::cout); + } catch (const std::exception &err) { + std::cerr << "vls-dap: " << err.what() << '\n'; + return 1; + } + return 0; +} diff --git a/src/debug/dap/Projection.cpp b/src/debug/dap/Projection.cpp new file mode 100644 index 0000000..8eb24ea --- /dev/null +++ b/src/debug/dap/Projection.cpp @@ -0,0 +1,163 @@ +#include "Projection.hpp" + +#include "../Fields.hpp" + +#include +#include +#include + +namespace vls::debug::dap { +std::int64_t argument_number(const Json::Object &arguments, std::string_view key, + std::int64_t maximum) { + auto n = integer(arguments, key); + if (!n || *n < 0 || *n > maximum) + throw RequestError("invalid integer argument " + std::string(key)); + return *n; +} + +namespace { +Json captured_source() { + return Json{Json::Object{{"name", text("input.cpp")}, {"sourceReference", number(1)}}}; +} + +struct Page { + std::size_t start, end; +}; +Page dap_page(const Json::Object &args, std::string_view start_key, std::string_view count_key, + std::size_t total) { + constexpr auto max_index = std::numeric_limits::max(); + const auto start = args.contains(start_key) ? argument_number(args, start_key, max_index) : 0; + const auto count = args.contains(count_key) ? argument_number(args, count_key, max_index) : 0; + const auto first = std::min(total, static_cast(start)); + return {first, + count ? first + std::min(total - first, static_cast(count)) : total}; +} + +std::string integer_value(const Json::Object &value) { + const auto width = integer(value, "precision"); + const auto bits = string_field(value, "bitsHex"); + const auto is_signed = Protocol::as_bool(Protocol::find_member(value, "signed")); + if (!width || *width < 1 || *width > 64 || !bits || !is_signed) + throw RequestError("invalid recorded integer"); + std::uint64_t word{}; + const auto [end, error] = std::from_chars(bits->data(), bits->data() + bits->size(), word, 16); + if (error != std::errc{} || end != bits->data() + bits->size()) + throw RequestError("invalid recorded bits"); + const auto sign = std::uint64_t{1} << (*width - 1); + if (*is_signed && (word & sign)) { + const auto mask = *width == 64 ? ~std::uint64_t{} : (sign << 1) - 1; + return "-" + std::to_string((~word & mask) + 1); + } + return std::to_string(word); +} + +Json variable(std::string_view name, std::string_view value) { + return Json{Json::Object{ + {"name", text(name)}, {"value", text(value)}, {"variablesReference", number(0)}}}; +} + +Json::Array frame_variables(const Json::Object &fields) { + Json::Array result; + const auto *value = Protocol::as_object(Protocol::find_member(fields, "value")); + if (value && string_field(*value, "kind") == "integer") { + result.push_back(variable("Result", integer_value(*value))); + result.push_back(variable("Bits", *string_field(*value, "bitsHex"))); + result.push_back(variable("Precision", std::to_string(*integer(*value, "precision")))); + result.push_back(variable( + "Signed", + *Protocol::as_bool(Protocol::find_member(*value, "signed")) ? "true" : "false")); + } else if (value) { + result.push_back( + variable("Result", string_field(*value, "reason").value_or("unavailable"))); + } + if (const auto provisional = + Protocol::as_bool(Protocol::find_member(fields, "valueProvisional"))) + result.push_back(variable("Provisional", *provisional ? "true" : "false")); + if (const auto outcome = string_field(fields, "outcome")) + result.push_back(variable("Outcome", *outcome)); + if (Protocol::as_bool(Protocol::find_member(fields, "cached")).value_or(false)) + result.push_back(variable("Cached", "true")); + return result; +} +} // namespace + +Json::Object inspect(std::string_view command, const Json::Object &args, + const ReplaySession &session, bool variable_paging) { + if (command == "vls/session") + return session.describe(); + if (command == "vls/timeline" || command == "vls/frames") { + if (!session.matches(args)) + throw RequestError("stale or incompatible inspection context"); + const auto start = argument_number(args, "start"); + const auto count = argument_number(args, "count"); + auto page = command == "vls/timeline" ? session.timeline(start, count) + : session.frames(start, count); + if (!page) + throw RequestError(page.error()); + return std::move(*page); + } + if (command == "loadedSources") { + Json::Array sources; + if (session.source_available()) + sources.push_back(captured_source()); + return {{"sources", Json{std::move(sources)}}}; + } + if (command == "source") { + if (!session.source_available() || argument_number(args, "sourceReference") != 1) + throw RequestError("unknown captured source"); + if (const auto *source = Protocol::find_member(args, "source")) { + const auto *fields = Protocol::as_object(source); + if (!fields || + (fields->contains("sourceReference") && integer(*fields, "sourceReference") != 1)) + throw RequestError("conflicting captured source reference"); + } + return {{"content", text(session.source_bytes())}, {"mimeType", text("text/x-c++src")}}; + } + if (!session.paused()) + throw RequestError("no active replay cursor"); + if (command == "threads") + return {{"threads", Json{Json::Array{Json{Json::Object{ + {"id", number(1)}, {"name", text("C++ constant evaluation")}}}}}}}; + if (command == "stackTrace") { + if (argument_number(args, "threadId") != 1) + throw RequestError("unknown replay thread"); + auto [start, end] = dap_page(args, "startFrame", "levels", session.frame_count()); + Json::Array frames; + for (auto i = start; i < end; ++i) { + const auto &fields = std::get(session.frame(i).value); + frames.push_back(Json{ + Json::Object{{"id", number(session.frame_handle(i))}, + {"name", text(string_field(fields, "name").value_or(""))}, + {"line", number(0)}, + {"column", number(0)}}}); + } + return {{"stackFrames", Json{std::move(frames)}}, + {"totalFrames", number(session.frame_count())}}; + } + if (command == "scopes") { + auto index = session.handle_index(argument_number(args, "frameId"), false); + if (!index) + throw RequestError("expired or unknown frame"); + Json::Object scope{{"name", text("Constant evaluation")}, + {"variablesReference", number(session.scope_handle(*index))}, + {"expensive", Json{false}}}; + return {{"scopes", Json{Json::Array{Json{std::move(scope)}}}}}; + } + if (command == "variables") { + auto index = session.handle_index(argument_number(args, "variablesReference"), true); + if (!index) + throw RequestError("expired or unknown variables reference"); + const auto filter = string_field(args, "filter"); + if (args.contains("filter") && filter != "named" && filter != "indexed") + throw RequestError("unknown variable filter"); + auto vars = filter == "indexed" + ? Json::Array{} + : frame_variables(std::get(session.frame(*index).value)); + if (!variable_paging) + return {{"variables", Json{std::move(vars)}}}; + const auto [start, end] = dap_page(args, "start", "count", vars.size()); + return {{"variables", Json{Json::Array(vars.begin() + start, vars.begin() + end)}}}; + } + throw RequestError("unsupported replay request"); +} +} // namespace vls::debug::dap diff --git a/src/debug/dap/Projection.hpp b/src/debug/dap/Projection.hpp new file mode 100644 index 0000000..7eb8d2d --- /dev/null +++ b/src/debug/dap/Projection.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include + +#include +#include + +namespace vls::debug::dap { +// Errors with a request sequence can be reported to the client and leave the session usable. +struct RequestError : std::runtime_error { + using std::runtime_error::runtime_error; +}; +std::int64_t argument_number(const Json::Object &, std::string_view key, + std::int64_t maximum = std::numeric_limits::max()); +Json::Object inspect(std::string_view command, const Json::Object &arguments, + const ReplaySession &session, bool variable_paging); +} // namespace vls::debug::dap diff --git a/src/debug/inspection/ReplaySession.cpp b/src/debug/inspection/ReplaySession.cpp new file mode 100644 index 0000000..a937cb4 --- /dev/null +++ b/src/debug/inspection/ReplaySession.cpp @@ -0,0 +1,215 @@ +#include + +#include "../Fields.hpp" +#include "Trace.hpp" + +#include + +#include +#include +#include +#include +#include + +namespace vls::debug { +namespace { +std::expected session_id() { + std::array bytes{}; + for (std::size_t used = 0; used < bytes.size();) { + const auto n = ::getrandom(bytes.data() + used, bytes.size() - used, 0); + if (n < 0 && errno == EINTR) + continue; + if (n <= 0) + return std::unexpected{"could not allocate a debug session identity"}; + used += static_cast(n); + } + constexpr std::string_view hex = "0123456789abcdef"; + std::string id; + for (auto byte : bytes) { + id += hex[byte >> 4]; + id += hex[byte & 15]; + } + return id; +} +} // namespace + +ReplaySession::ReplaySession(std::shared_ptr recording, std::string id) + : recording_(std::move(recording)), id_(std::move(id)), + source_available_(Void::Unicode::validate_utf8(recording_->source_bytes()).has_value()) {} + +std::expected ReplaySession::open(const std::filesystem::path &path) { + auto recording = gcc::ReplayRecording::open(path); + if (!recording) + return std::unexpected{std::move(recording.error())}; + auto id = session_id(); + if (!id) + return std::unexpected{std::move(id.error())}; + return ReplaySession(std::move(*recording), std::move(*id)); +} + +Json::Object ReplaySession::identity() const { + return {{"schemaVersion", number(1)}, + {"sessionId", text(id_)}, + {"generation", number(generation_)}}; +} + +bool ReplaySession::matches(const Json::Object &arguments) const { + return integer(arguments, "schemaVersion") == 1 && + string_field(arguments, "sessionId") == id_ && + integer(arguments, "generation") == generation_; +} + +Json::Object ReplaySession::describe() const { + auto result = identity(); + const auto meta = recording_->metadata(); + Json::Object record{{"partial", Json{meta.partial}}, + {"corrupt", Json{meta.corrupt}}, + {"eventCount", number(recording_->event_count())}, + {"outcome", meta.outcome ? text(*meta.outcome) : Json{nullptr}}, + {"exitCode", meta.exit_code ? number(*meta.exit_code) : Json{nullptr}}}; + if (meta.journal_error) + record.emplace("journalError", text(*meta.journal_error)); + result.emplace("recording", Json{std::move(record)}); + result.emplace("mode", text("replay")); + result.emplace("backend", text(meta.backend)); + result.emplace("compilerPid", number(meta.pid)); + result.emplace("compilerSha256", text(meta.compiler_sha256)); + result.emplace("sourceSha256", text(meta.source_sha256)); + result.emplace("sourceByteLength", number(source_bytes().size())); + result.emplace("sourceAvailable", Json{source_available_}); + if (source_available_) + result.emplace("sourceReference", number(1)); + result.emplace("eventSequence", sequence_ ? number(*sequence_) : Json{nullptr}); + result.emplace("pauseKind", text(pause_kind_)); + return result; +} + +std::string_view ReplaySession::source_bytes() const { return recording_->source_bytes(); } + +std::size_t ReplaySession::frame_count() const { + if (!paused()) + return 0; + return std::get(std::get(cursor_.value).at("frames").value).size(); +} + +const Json &ReplaySession::frame(std::size_t index) const { + const auto &frames = + std::get(std::get(cursor_.value).at("frames").value); + return frames.at(frames.size() - 1 - index); +} + +std::int64_t ReplaySession::frame_handle(std::size_t index) const { + return frame_base_ + static_cast(index); +} +std::int64_t ReplaySession::scope_handle(std::size_t index) const { + return frame_handle(index) + static_cast(frame_count()); +} +std::optional ReplaySession::handle_index(std::int64_t handle, bool scope) const { + const auto base = scope ? scope_handle(0) : frame_base_; + if (handle < base || handle >= base + static_cast(frame_count())) + return {}; + return static_cast(handle - base); +} + +std::expected ReplaySession::seek(std::uint32_t sequence) { + if (finished_) + return std::unexpected{"replay session has terminated"}; + auto page = recording_->event_page(sequence, 1); + if (!page || page->empty()) + return std::unexpected{"event is outside the verified prefix"}; + auto cursor = recording_->cursor_at(sequence); + if (!cursor) + return std::unexpected{std::move(cursor.error())}; + const auto *frames = + Protocol::as_array(Protocol::find_member(std::get(cursor->value), "frames")); + const auto handles = 2 * static_cast(frames->size()); + if (next_handle_ + handles - 1 > std::numeric_limits::max()) + return std::unexpected{"debug handle limit reached"}; + const auto kind = page->front().kind; + pause_kind_ = kind == "stopped" ? "recordedStop" : kind == "value" ? "value" : "event"; + sequence_ = sequence; + cursor_ = std::move(*cursor); + ++generation_; + frame_base_ = next_handle_; + next_handle_ += handles; + return {}; +} + +std::expected ReplaySession::initial_position() { + auto first = move_to_value(true); + if (!first || *first || !recording_->event_count()) + return first; + // A compiler can stop producing events before its first integral return. Its + // last verified event still owns an inspectable stack and earlier history. + auto cursor = seek(static_cast(recording_->event_count() - 1)); + if (!cursor) + return std::unexpected{std::move(cursor.error())}; + return true; +} + +std::expected ReplaySession::move_to_value(bool forward) { + if (finished_) + return std::unexpected{"replay session has terminated"}; + auto point = + forward ? recording_->next_value(sequence_) : recording_->previous_value(sequence_); + if (!point) + return std::unexpected{std::move(point.error())}; + if (!point->has_value()) + return false; + auto moved = seek((*point)->stop_sequence.value_or((*point)->value_sequence)); + if (!moved) + return std::unexpected{std::move(moved.error())}; + return true; +} + +void ReplaySession::finish() { + if (finished_) + return; + finished_ = true; + ++generation_; + sequence_.reset(); + cursor_ = Json{nullptr}; + pause_kind_ = "none"; +} + +std::expected ReplaySession::timeline(std::size_t start, + std::size_t count) const { + auto page = recording_->event_page(start, count); + if (!page) + return std::unexpected{std::move(page.error())}; + Json::Array events; + for (const auto &entry : *page) { + Json::Object fields{{"sequence", number(entry.sequence)}, {"kind", text(entry.kind)}}; + if (entry.frame) + fields.emplace("frame", number(*entry.frame)); + if (entry.parent) + fields.emplace("parent", number(*entry.parent)); + if (entry.acknowledged_stop) { + fields.emplace("acknowledgedStop", number(*entry.acknowledged_stop)); + fields.emplace("acknowledgedAction", text(*entry.acknowledged_action)); + } + events.push_back(Json{std::move(fields)}); + } + auto body = identity(); + body.emplace("total", number(recording_->event_count())); + body.emplace("events", Json{std::move(events)}); + return body; +} + +std::expected ReplaySession::frames(std::size_t start, + std::size_t count) const { + if (!paused() || start > frame_count() || count > gcc::ReplayRecording::max_page_size) + return std::unexpected{"frame page is unavailable"}; + Json::Array frames; + const auto end = start + std::min(count, frame_count() - start); + for (auto i = start; i < end; ++i) + frames.push_back(frame(i)); + auto result = identity(); + result.emplace("total", number(frame_count())); + result.emplace("frames", Json{std::move(frames)}); + const auto &cursor = std::get(cursor_.value); + for (const auto *key : {"lastLeave", "stop", "pendingAction", "frontendEnded", "terminal"}) + result.emplace(key, cursor.at(key)); + return result; +} +} // namespace vls::debug diff --git a/src/debug/live/LiveSession.cpp b/src/debug/live/LiveSession.cpp new file mode 100644 index 0000000..cc1df88 --- /dev/null +++ b/src/debug/live/LiveSession.cpp @@ -0,0 +1,327 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::debug::live { +namespace P = Void::LanguageServer::Protocol; +using Json = P::Json; +using Clock = std::chrono::steady_clock; +using namespace std::chrono_literals; + +namespace { +constexpr std::size_t max_stderr_bytes = 256 * 1024; +constexpr std::size_t max_buffer_bytes = 256 * 1024; + +bool write_bounded(int fd, std::string_view bytes) { + const auto deadline = Clock::now() + 2s; + while (!bytes.empty() && Clock::now() < deadline) { + const auto written = ::write(fd, bytes.data(), bytes.size()); + if (written > 0) { + bytes.remove_prefix(static_cast(written)); + continue; + } + if (written < 0 && errno == EINTR) + continue; + if (written < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + pollfd pipe{fd, POLLOUT, 0}; + if (::poll(&pipe, 1, 10) < 0 && errno != EINTR) + return false; + continue; + } + return false; + } + return bytes.empty(); +} + +const Json *member(const Json &value, std::string_view key) { + const auto *object = P::as_object(&value); + return object ? P::find_member(*object, key) : nullptr; +} + +std::optional integer(const Json *value) { + if (!value) + return std::nullopt; + if (const auto *number = std::get_if(&value->value)) + return *number; + return std::nullopt; +} +} // namespace + +struct LiveSession::State_ { + explicit State_(Options value) : options(std::move(value)) {} + + Options options; + Void::Process::Child child; + std::string buffer, errors, nonce, outcome, reason; + State state{State::idle}; + std::optional current; + std::uint64_t generation{}; + bool child_running{true}; + Clock::time_point deadline{}; + + struct Notice { + std::string kind; + std::optional stop; + std::optional snapshot; + std::string outcome, reason; + }; + + bool reap() { + if (!child_running) + return true; + auto waited = child.try_wait(); + if (!waited) + return false; + if (!*waited) + return true; + child_running = false; + return true; + } + + // Reads one complete notice line within the deadline. + std::expected next_notice() { + while (true) { + const auto newline = buffer.find('\n'); + if (newline != std::string::npos) { + const auto line = buffer.substr(0, newline); + buffer.erase(0, newline + 1); + if (line.empty()) + continue; + if (line.size() > options.max_notice_bytes) + return std::unexpected("worker notice exceeds its bound"); + auto parsed = P::parse_json(line, 8); + if (!parsed) + return std::unexpected("worker notice is not valid JSON"); + const auto *kind = P::as_string(member(*parsed, "kind")); + if (!kind) + return std::unexpected("worker notice lacks a kind"); + Notice notice{.kind = *kind}; + if (*kind == "started" || *kind == "stopped") { + const auto *nonce = P::as_string(member(*parsed, "nonce")); + if (!nonce || nonce->size() != 32) + return std::unexpected("worker notice has an invalid nonce"); + this->nonce = *nonce; + } + if (*kind == "stopped") { + const auto sequence = integer(member(*parsed, "stop")); + if (!sequence || *sequence < 1 || + *sequence > std::numeric_limits::max()) + return std::unexpected("worker stop is invalid"); + notice.stop = static_cast(*sequence); + } else if (*kind == "inspection") { + const auto *snapshot = member(*parsed, "snapshot"); + if (!snapshot) + return std::unexpected("inspection notice lacks a snapshot"); + auto encoded = P::serialize_json(*snapshot); + if (!encoded || encoded->size() > options.max_notice_bytes) + return std::unexpected("inspection snapshot exceeds its bound"); + notice.snapshot = *snapshot; + } else if (*kind == "inspectionLimit") { + return std::unexpected("inspection snapshot exceeds the worker limit"); + } else if (*kind == "finished") { + const auto *outcome = P::as_string(member(*parsed, "outcome")); + const auto *reason = P::as_string(member(*parsed, "reason")); + if (!outcome || !reason || reason->size() > 1024) + return std::unexpected("worker completion notice is invalid"); + notice.outcome = *outcome; + notice.reason = *reason; + } else if (*kind == "rejected") { + return std::unexpected("the worker rejected the command"); + } + return notice; + } + if (Clock::now() >= deadline) + return std::unexpected("worker notice deadline expired"); + pollfd pipes[]{{child.stdout_fd(), POLLIN, 0}, {child.stderr_fd(), POLLIN, 0}}; + const auto remaining = + std::chrono::duration_cast(deadline - Clock::now()); + const int count = ::poll(pipes, 2, + static_cast(std::max( + 1, std::min(remaining.count(), 50)))); + if (count < 0 && errno != EINTR) + return std::unexpected("cannot poll the worker"); + if (count <= 0) + continue; + if (pipes[0].revents != 0) { + char bytes[8192]; + const auto read = ::read(child.stdout_fd(), bytes, sizeof bytes); + if (read == 0) { + reap(); + return std::unexpected("worker closed its output"); + } + if (read < 0 && errno != EAGAIN && errno != EINTR) + return std::unexpected("cannot read the worker output"); + if (read > 0) { + buffer.append(bytes, static_cast(read)); + if (buffer.size() > max_buffer_bytes) + return std::unexpected("worker output exceeds its bound"); + } + } + if (pipes[1].revents != 0) { + char bytes[8192]; + const auto read = ::read(child.stderr_fd(), bytes, sizeof bytes); + if (read > 0 && errors.size() < max_stderr_bytes) + errors.append(bytes, std::min(static_cast(read), + max_stderr_bytes - errors.size())); + } + } + } + + bool send(std::string_view action) { + if (nonce.size() != 32 || !current) + return false; + const std::string line = + nonce + " " + std::to_string(current->sequence) + " " + std::string{action} + "\n"; + return write_bounded(child.stdin_fd(), line); + } + + std::expected, std::string> move(std::string_view action) { + if (state != State::stopped || !current) + return std::unexpected("the session is not stopped"); + deadline = Clock::now() + options.deadline; + if (!send(action)) + return std::unexpected("cannot send the control command"); + state = State::running; + while (true) { + auto notice = next_notice(); + if (!notice) + return std::unexpected(notice.error()); + if (notice->kind == "stopped") { + current = Stop{++generation, *notice->stop}; + state = State::stopped; + return current; + } + if (notice->kind == "finished") { + finish(notice->outcome, notice->reason); + return std::optional{}; + } + } + } + + void finish(std::string_view result, std::string_view detail) { + outcome = std::string{result}; + reason = std::string{detail}; + current.reset(); + state = result == "completed" ? State::completed + : result == "cancelled" ? State::cancelled + : State::failed; + } +}; + +LiveSession::LiveSession(Options options) : state_(std::make_unique(std::move(options))) {} + +LiveSession::~LiveSession() { + if (state_->state == State::running || state_->state == State::stopped) { + static_cast(state_->reap()); + if (!state_->child_running) + return; + if (state_->current) + state_->send("cancel"); + else + write_bounded(state_->child.stdin_fd(), state_->nonce + " cancel\n"); + state_->child.terminate(100ms); + } +} + +std::expected LiveSession::start() { + auto &state = *state_; + if (state.state != State::idle) + return std::unexpected("the session already started"); + state.state = State::running; + state.deadline = Clock::now() + state.options.deadline; + Void::Process::SpawnOptions spawn; + spawn.executable = state.options.worker; + spawn.arguments = {"run", state.options.compiler.native(), state.options.compiler_sha256, + state.options.source.native(), state.options.trace.native()}; + if (state.options.stepping) + spawn.arguments.push_back("--step"); + spawn.working_directory = state.options.trace.parent_path(); + spawn.search_path = false; + auto child = Void::Process::spawn(spawn); + if (!child) + return std::unexpected("could not start the private GCC worker: " + + child.error().message()); + state.child = std::move(*child); + while (true) { + auto notice = state.next_notice(); + if (!notice) + return std::unexpected(notice.error()); + if (notice->kind == "stopped") { + state.current = Stop{++state.generation, *notice->stop}; + state.state = State::stopped; + return *state.current; + } + if (notice->kind == "finished") { + state.finish(notice->outcome, notice->reason); + return std::unexpected("the session finished before its first stop: " + state.reason); + } + } +} + +std::expected, std::string> LiveSession::step() { return state_->move("step"); } + +std::expected, std::string> LiveSession::continue_run() { + return state_->move("continue"); +} + +std::expected LiveSession::cancel() { + auto &state = *state_; + if (state.state == State::completed || state.state == State::failed || + state.state == State::cancelled) + return {}; + if (state.state == State::idle) + return std::unexpected("the session did not start"); + state.deadline = Clock::now() + state.options.deadline; + if (state.current) + state.send("cancel"); + else + write_bounded(state.child.stdin_fd(), state.nonce + " cancel\n"); + state.state = State::running; + while (true) { + auto notice = state.next_notice(); + if (!notice) + return std::unexpected(notice.error()); + if (notice->kind == "finished") { + state.finish(notice->outcome, notice->reason); + if (state.state == State::cancelled) + return {}; + return std::unexpected("the worker finished as " + state.outcome + ": " + state.reason); + } + } +} + +std::expected LiveSession::inspect() { + auto &state = *state_; + if (state.state != State::stopped || !state.current) + return std::unexpected("the session is not stopped"); + state.deadline = Clock::now() + state.options.deadline; + if (!state.send("inspect")) + return std::unexpected("cannot send the inspection command"); + while (true) { + auto notice = state.next_notice(); + if (!notice) + return std::unexpected(notice.error()); + if (notice->kind == "inspection") + return *notice->snapshot; + if (notice->kind == "finished") { + state.finish(notice->outcome, notice->reason); + return std::unexpected("the session finished during inspection: " + state.reason); + } + } +} + +State LiveSession::state() const { return state_->state; } +std::optional LiveSession::stop() const { return state_->current; } +std::string LiveSession::outcome() const { return state_->outcome; } +std::string LiveSession::reason() const { return state_->reason; } + +} // namespace vls::debug::live diff --git a/src/features/Completion.cpp b/src/features/Completion.cpp new file mode 100644 index 0000000..87e5bd6 --- /dev/null +++ b/src/features/Completion.cpp @@ -0,0 +1,135 @@ +#include + +#include +#include +#include +#include +#include + +namespace vls::features::completion { + +namespace { +bool identifier(char ch) { + return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || + ch == '_'; +} + +int priority(Kind kind) { + switch (kind) { + case Kind::type: + return 0; + case Kind::function: + return 1; + case Kind::field: + return 2; + case Kind::variable: + return 3; + case Kind::namespace_: + return 4; + case Kind::module: + return 5; + case Kind::keyword: + return 6; + case Kind::unknown: + return 7; + } + return 7; +} + +std::string bounded(std::string value, std::size_t limit) { + if (value.size() > limit) + value.resize(limit); + return value; +} +} // namespace + +std::string_view prefix_at(std::string_view text, std::size_t offset) { + if (offset > text.size()) + return {}; + std::size_t start = offset; + while (start > 0 && identifier(text[start - 1])) + --start; + const auto prefix = text.substr(start, offset - start); + if (prefix.empty() || (prefix.front() >= '0' && prefix.front() <= '9')) + return {}; + return prefix; +} + +Result complete(std::span candidates, std::string_view text, std::size_t offset, + const Limits &limits) { + Result result; + const auto prefix = prefix_at(text, offset); + const std::size_t start = offset - prefix.size(); + std::set> seen; + std::vector items; + for (const auto &candidate : candidates) { + if (candidate.label.empty() || candidate.label.size() > limits.labelBytes || + !candidate.label.starts_with(prefix)) + continue; + if (!seen.emplace(candidate.label, candidate.kind).second) + continue; + items.push_back( + Item{.label = candidate.label, + .kind = candidate.kind, + .detail = bounded(candidate.detail, limits.detailBytes), + .provenance = bounded(candidate.provenance, limits.provenanceBytes), + .sort_text = std::to_string(priority(candidate.kind)) + candidate.label, + .identity = candidate.identity, + .replacement_start = start, + .replacement_end = offset}); + } + std::ranges::sort(items, [](const Item &left, const Item &right) { + return std::tie(left.sort_text, left.label) < std::tie(right.sort_text, right.label); + }); + if (items.size() > limits.candidates) + items.resize(limits.candidates); + result.items = std::move(items); + return result; +} + +Resolved resolve(const Identity &identity, std::uint64_t captured_generation, + std::uint64_t current_generation, std::span current, + const Limits &limits) { + Resolved result; + if (captured_generation != current_generation) { + result.status = Resolved::Status::stale; + return result; + } + const auto found = std::ranges::find_if( + current, [&identity](const Detail &entry) { return entry.identity == identity; }); + if (found == current.end()) { + result.status = Resolved::Status::unknown; + return result; + } + result.status = Resolved::Status::resolved; + result.detail = bounded(found->detail, limits.detailBytes); + // A fence longer than any backtick run in the content cannot be closed by it. + std::size_t longest{}; + std::size_t run{}; + for (const char ch : found->detail) { + run = ch == '`' ? run + 1 : 0; + longest = std::max(longest, run); + } + const std::string fence(std::max(3, longest + 1), '`'); + const std::string head = fence + "text\n"; + const std::string closing = "\n" + fence + "\n"; + // The closing fence is always kept: a truncated value must never leave an + // open fence that lets content escape into the editor's Markdown. + const std::size_t fixed = head.size() + closing.size(); + const std::size_t budget = + limits.detailBytes > fixed ? limits.detailBytes - fixed : std::size_t{}; + std::string documentation = head + result.detail.substr(0, budget) + closing; + const auto append = [&](std::string piece) { + if (documentation.size() + piece.size() <= limits.detailBytes) + documentation += std::move(piece); + }; + if (!found->provenance.empty()) + append("\nProvenance: " + bounded(found->provenance, limits.provenanceBytes) + "\n"); + append("\nLocation: `" + bounded(found->identity.path, limits.detailBytes) + ":" + + std::to_string(found->identity.line) + ":" + std::to_string(found->identity.character) + + "`\n"); + result.documentation = std::move(documentation); + return result; +} + +} // namespace vls::features::completion diff --git a/src/features/IndexNavigation.cpp b/src/features/IndexNavigation.cpp new file mode 100644 index 0000000..9bf4a83 --- /dev/null +++ b/src/features/IndexNavigation.cpp @@ -0,0 +1,74 @@ +#include + +#include +#include +#include +#include + +namespace vls::features { +namespace { +using Key = std::tuple; + +navigation::Location location(const index::Location &value) { + return {value.path, {value.line, value.character, value.endLine, value.endCharacter}}; +} + +navigation::Range range(const index::Location &value) { + return {{value.line, value.character}, {value.endLine, value.endCharacter}}; +} + +const IndexedSource *source_of(std::span sources, std::string_view path) { + const auto found = std::ranges::find_if( + sources, [path](const IndexedSource &source) { return source.path == path; }); + return found == sources.end() ? nullptr : &*found; +} +} // namespace + +std::size_t ingest_index_facts(navigation::FactSet &set, const index::Generation &generation, + std::span sources, std::size_t limit) { + std::set known_contexts; + for (const auto &context : set.contexts) + known_contexts.insert(context.context); + for (const auto &[name, coverage] : generation.contexts()) + if (!known_contexts.contains(name)) + set.contexts.push_back( + {name, coverage.complete, coverage.complete ? "" : "index coverage incomplete"}); + + std::set present; + for (const auto &fact : set.facts) + present.emplace(fact.binding, fact.source, fact.use); + + std::size_t added{}; + for (const auto &record : generation.symbols()) { + if (added >= limit) + break; + navigation::Binding binding; + binding.name = record.name; + if (record.definition) + binding.definition = location(*record.definition); + std::vector uses{&record.location}; + for (const auto &reference : record.references) + uses.push_back(&reference); + for (const auto *use : uses) { + if (added >= limit) + break; + const auto *source = source_of(sources, use->path); + navigation::Fact fact; + fact.binding = binding; + fact.context = "symbol-index"; + fact.source = use->path; + fact.content = source ? source->content : std::string{}; + fact.use = range(*use); + fact.editable = source != nullptr && source->editable && !fact.content.empty(); + fact.provenance = + record.provenance.empty() ? std::string{"symbol-index"} : record.provenance; + if (!present.emplace(fact.binding, fact.source, fact.use).second) + continue; + set.facts.push_back(std::move(fact)); + ++added; + } + } + return added; +} + +} // namespace vls::features diff --git a/src/features/SignatureHelp.cpp b/src/features/SignatureHelp.cpp new file mode 100644 index 0000000..f6b42e9 --- /dev/null +++ b/src/features/SignatureHelp.cpp @@ -0,0 +1,258 @@ +#include + +#include +#include + +namespace vls::features::signature { +namespace { +bool word(char ch) { + return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || + ch == '_' || ch == ':'; +} + +// Opens an angle bracket only where a template argument list plausibly starts: +// after a name, '>' or ':' and not before '=' or '<' (operators). +bool opens_angle(std::string_view text, std::size_t index) { + if (index == 0 || index + 1 >= text.size()) + return false; + const char previous = text[index - 1]; + const char next = text[index + 1]; + return (word(previous) || previous == '>' || previous == '*') && next != '=' && next != '<'; +} + +std::string bounded(std::string value, std::size_t limit) { + if (value.size() > limit) + value.resize(limit); + return value; +} + +std::string trim(std::string_view text) { + const auto first = text.find_first_not_of(" \t\r\n"); + if (first == std::string_view::npos) + return {}; + const auto last = text.find_last_not_of(" \t\r\n"); + return std::string{text.substr(first, last - first + 1)}; +} +} // namespace + +Signature parse(std::string_view signature, const Limits &limits) { + Signature result; + result.label = bounded(std::string{signature}, limits.labelBytes); + const auto open = signature.find('('); + if (open == std::string_view::npos) + return result; + const auto close = signature.find_last_of(')'); + if (close == std::string_view::npos || close < open) + return result; + const auto list = signature.substr(open + 1, close - open - 1); + if (trim(list).empty()) + return result; + int paren{}, square{}, brace{}, angle{}; + std::size_t start{}; + const auto emit = [&](std::size_t end) { + const auto piece = list.substr(start, end - start); + const auto cleaned = trim(piece); + if (cleaned.empty()) + return; + const auto first = piece.find(cleaned.front()); + Parameter parameter; + parameter.label = bounded(cleaned, limits.parameterBytes); + if (first != std::string_view::npos && first < limits.labelBytes) { + const auto begin = static_cast(open + 1 + start + first); + parameter.range = + std::pair{begin, static_cast(std::min( + begin + parameter.label.size(), limits.labelBytes))}; + } + if (result.parameters.size() < limits.parameters) + result.parameters.push_back(std::move(parameter)); + }; + for (std::size_t index = 0; index != list.size(); ++index) { + const char ch = list[index]; + switch (ch) { + case '(': + ++paren; + break; + case ')': + paren = std::max(0, paren - 1); + break; + case '[': + ++square; + break; + case ']': + square = std::max(0, square - 1); + break; + case '{': + ++brace; + break; + case '}': + brace = std::max(0, brace - 1); + break; + case '<': + if (opens_angle(list, index)) + ++angle; + break; + case '>': + angle = std::max(0, angle - 1); + break; + case ',': + if (paren == 0 && square == 0 && brace == 0 && angle == 0) { + emit(index); + start = index + 1; + } + break; + default: + break; + } + } + emit(list.size()); + return result; +} + +std::uint32_t active_parameter(std::string_view text, std::size_t offset, const Limits &limits) { + if (offset > text.size()) + offset = text.size(); + const std::size_t lower = offset > limits.scanBytes ? offset - limits.scanBytes : 0; + std::size_t open{}; + bool found{}; + int depth{}; + for (std::size_t index = offset; index > lower; --index) { + const char ch = text[index - 1]; + if (ch == ')') + ++depth; + else if (ch == '(') { + if (depth == 0) { + open = index - 1; + found = true; + break; + } + --depth; + } + } + if (!found) + return 0; + std::uint32_t commas{}; + int paren{}, square{}, brace{}; + char quote{'\0'}; + bool line_comment{}; + bool block_comment{}; + for (std::size_t index = open + 1; index < offset && index < open + 1 + limits.scanBytes; + ++index) { + const char ch = text[index]; + const char next = index + 1 < offset ? text[index + 1] : '\0'; + if (line_comment) { + if (ch == '\n') + line_comment = false; + continue; + } + if (block_comment) { + if (ch == '*' && next == '/') { + block_comment = false; + ++index; + } + continue; + } + if (quote != '\0') { + if (ch == '\\') + ++index; + else if (ch == quote) + quote = '\0'; + continue; + } + if (ch == '/' && next == '/') { + line_comment = true; + ++index; + } else if (ch == '/' && next == '*') { + block_comment = true; + ++index; + } else if (ch == '"' || ch == '\'') { + quote = ch; + } else if (ch == '(') { + ++paren; + } else if (ch == ')') { + paren = std::max(0, paren - 1); + } else if (ch == '[') { + ++square; + } else if (ch == ']') { + square = std::max(0, square - 1); + } else if (ch == '{') { + ++brace; + } else if (ch == '}') { + brace = std::max(0, brace - 1); + } else if (ch == ',' && paren == 0 && square == 0 && brace == 0) { + ++commas; + } + } + return commas; +} + +bool in_call(std::string_view text, std::size_t use_start, std::size_t use_end, std::size_t offset, + const Limits &limits) { + if (offset > text.size() || use_end > offset || use_start > use_end) + return false; + const auto open = text.find('(', use_end); + if (open == std::string_view::npos || open >= offset) + return false; + const auto stop = std::min({text.size(), offset, open + 1 + limits.scanBytes}); + int depth{}; + char quote{'\0'}; + bool line_comment{}; + bool block_comment{}; + for (std::size_t index = open; index < stop; ++index) { + const char ch = text[index]; + const char next = index + 1 < stop ? text[index + 1] : '\0'; + if (line_comment) { + if (ch == '\n') + line_comment = false; + continue; + } + if (block_comment) { + if (ch == '*' && next == '/') { + block_comment = false; + ++index; + } + continue; + } + if (quote != '\0') { + if (ch == '\\') + ++index; + else if (ch == quote) + quote = '\0'; + continue; + } + if (ch == '/' && next == '/') { + line_comment = true; + ++index; + } else if (ch == '/' && next == '*') { + block_comment = true; + ++index; + } else if (ch == '"' || ch == '\'') { + quote = ch; + } else if (ch == '(') { + ++depth; + } else if (ch == ')') { + if (--depth == 0) + return false; + } + } + return depth > 0; +} + +Result build(std::span signatures, std::string_view text, std::size_t offset, + const Limits &limits) { + Result result; + for (const auto &candidate : signatures) { + if (result.signatures.size() >= limits.signatures) + break; + if (candidate.empty()) + continue; + auto parsed = parse(candidate, limits); + if (parsed.label.empty()) + continue; + result.signatures.push_back(std::move(parsed)); + } + if (!result.signatures.empty()) + result.active_parameter = active_parameter(text, offset, limits); + return result; +} + +} // namespace vls::features::signature diff --git a/src/index/SymbolIndex.cpp b/src/index/SymbolIndex.cpp new file mode 100644 index 0000000..cf45964 --- /dev/null +++ b/src/index/SymbolIndex.cpp @@ -0,0 +1,709 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::index { +namespace fs = std::filesystem; +namespace P = Void::LanguageServer::Protocol; +using Json = P::Json; + +namespace { +constexpr std::size_t max_json_depth = 8; +constexpr std::int64_t snapshot_schema = 2; +constexpr std::int64_t legacy_snapshot_schema = 1; +const char *backend_name = "vls-symbol-index"; + +bool plain(std::string_view text, std::size_t limit) { + return !text.empty() && text.size() <= limit && + std::ranges::none_of(text, [](unsigned char c) { return c == 0; }); +} + +bool valid_location(const Location &location, const Limits &limits) { + return plain(location.path, limits.pathBytes) && location.endLine >= location.line && + (location.endLine != location.line || location.endCharacter >= location.character); +} + +bool valid_record(const SymbolRecord &record, const Limits &limits) { + if (!plain(record.name, limits.nameBytes) || !valid_location(record.location, limits) || + record.references.size() > limits.referencesPerRecord) + return false; + if (record.definition && !valid_location(*record.definition, limits)) + return false; + return std::ranges::all_of( + record.references, [&](const auto &location) { return valid_location(location, limits); }); +} + +Json location_json(const Location &location) { + return Json{Json::Object{{"path", Json{location.path}}, + {"line", Json{std::int64_t{location.line}}}, + {"character", Json{std::int64_t{location.character}}}, + {"endLine", Json{std::int64_t{location.endLine}}}, + {"endCharacter", Json{std::int64_t{location.endCharacter}}}}}; +} + +Json record_json(const SymbolRecord &record) { + Json::Array references; + for (const auto &reference : record.references) + references.push_back(location_json(reference)); + Json::Object fields{{"name", Json{record.name}}, + {"kind", Json{std::int64_t{static_cast(record.kind)}}}, + {"location", location_json(record.location)}, + {"references", Json{std::move(references)}}, + {"provenance", Json{record.provenance}}}; + if (record.definition) + fields.emplace("definition", location_json(*record.definition)); + return Json{std::move(fields)}; +} + +std::optional text(const Json *value, std::size_t limit = 4096) { + const auto *string = value ? P::as_string(value) : nullptr; + if (!string || !plain(*string, limit)) + return std::nullopt; + return *string; +} + +std::optional coordinate(const Json *value) { + if (!value) + return std::nullopt; + const auto *number = std::get_if(&value->value); + if (!number || *number < 0 || *number > std::numeric_limits::max()) + return std::nullopt; + return static_cast(*number); +} + +std::optional read_location(const Json *value, const Limits &limits) { + const auto *fields = value ? P::as_object(value) : nullptr; + if (!fields) + return std::nullopt; + const auto path = text(P::find_member(*fields, "path"), limits.pathBytes); + const auto line = coordinate(P::find_member(*fields, "line")); + const auto character = coordinate(P::find_member(*fields, "character")); + const auto end_line = coordinate(P::find_member(*fields, "endLine")); + const auto end_character = coordinate(P::find_member(*fields, "endCharacter")); + if (!path || !line || !character || !end_line || !end_character) + return std::nullopt; + Location location{*path, *line, *character, *end_line, *end_character}; + return valid_location(location, limits) ? std::optional{location} : std::nullopt; +} + +std::optional read_record(const Json &value, const Limits &limits) { + const auto *fields = P::as_object(&value); + if (!fields) + return std::nullopt; + const auto name = text(P::find_member(*fields, "name"), limits.nameBytes); + const auto kind = coordinate(P::find_member(*fields, "kind")); + const auto provenance = text(P::find_member(*fields, "provenance"), limits.nameBytes); + const auto location = read_location(P::find_member(*fields, "location"), limits); + if (!name || !kind || !provenance || !location || *kind > static_cast(SymbolKind::module)) + return std::nullopt; + SymbolRecord record; + record.name = *name; + record.kind = static_cast(*kind); + record.provenance = *provenance; + record.location = *location; + if (const auto *definition = P::find_member(*fields, "definition")) { + auto parsed = read_location(definition, limits); + if (!parsed) + return std::nullopt; + record.definition = *parsed; + } + const auto *references = P::as_array(P::find_member(*fields, "references")); + if (!references || references->size() > limits.referencesPerRecord) + return std::nullopt; + for (const auto &reference : *references) { + auto parsed = read_location(&reference, limits); + if (!parsed) + return std::nullopt; + record.references.push_back(*parsed); + } + return valid_record(record, limits) ? std::optional{record} : std::nullopt; +} + +struct ContextEntry { + std::vector dependencies; + std::map sources; + std::vector records; + bool complete{true}; + std::string reason; +}; + +struct OverlayEntry { + std::string content; + std::vector records; +}; + +enum class SnapshotStatus { ok, incompatible, corrupt, oversized }; + +struct ParsedSnapshot { + std::map contexts; + std::map overlays; + std::uint64_t generation{}; + bool migrated{}; +}; + +std::string digest_of(std::string_view bytes) { + auto digest = Void::Crypto::sha256(bytes); + return digest ? Void::Encoding::Hex::encode(*digest) : std::string{}; +} + +// Classifies snapshot bytes without touching index state. Schema 1 is accepted +// and flagged for migration; an unknown schema or backend is incompatible, and +// malformed content or a digest mismatch is corrupt. +SnapshotStatus parse_snapshot(std::string_view bytes, const Limits &limits, ParsedSnapshot &out) { + if (bytes.size() > limits.snapshotBytes) + return SnapshotStatus::oversized; + auto parsed = P::parse_json(bytes, max_json_depth); + if (!parsed) + return SnapshotStatus::corrupt; + const auto *root = P::as_object(&*parsed); + if (!root) + return SnapshotStatus::corrupt; + const auto *schema = P::find_member(*root, "schema"); + const auto *backend = P::as_string(P::find_member(*root, "backend")); + const auto schema_value = schema ? std::get_if(&schema->value) : nullptr; + if (!schema_value || !backend || *backend != backend_name || + (*schema_value != snapshot_schema && *schema_value != legacy_snapshot_schema)) + return SnapshotStatus::incompatible; + if (*schema_value == snapshot_schema) { + const auto *digest = P::as_string(P::find_member(*root, "digest")); + if (!digest || digest->size() != 64) + return SnapshotStatus::corrupt; + auto payload = *root; + payload.erase("digest"); + auto encoded = P::serialize_json(Json{std::move(payload)}); + if (!encoded || digest_of(*encoded) != *digest) + return SnapshotStatus::corrupt; + } + const auto *generation = P::find_member(*root, "generation"); + const auto *contexts = P::as_array(P::find_member(*root, "contexts")); + const auto *overlays = P::as_array(P::find_member(*root, "overlays")); + const auto generation_value = + generation ? std::get_if(&generation->value) : nullptr; + if (!generation_value || *generation_value < 0 || !contexts || !overlays) + return SnapshotStatus::corrupt; + out.generation = static_cast(*generation_value); + out.migrated = *schema_value == legacy_snapshot_schema; + std::size_t total{}; + for (const auto &item : *contexts) { + const auto *fields = P::as_object(&item); + if (!fields) + return SnapshotStatus::corrupt; + const auto name = text(P::find_member(*fields, "context"), limits.nameBytes); + const auto complete = P::as_bool(P::find_member(*fields, "complete")); + const auto *reason = P::as_string(P::find_member(*fields, "reason")); + const auto *dependencies = P::as_array(P::find_member(*fields, "dependencies")); + const auto *sources = P::as_array(P::find_member(*fields, "sources")); + const auto *records = P::as_array(P::find_member(*fields, "records")); + if (!name || !complete || !reason || reason->size() > limits.nameBytes || !dependencies || + dependencies->size() > limits.contexts || !sources || !records || + records->size() > limits.recordsPerContext || out.contexts.size() >= limits.contexts) + return SnapshotStatus::corrupt; + ContextEntry entry; + entry.complete = *complete; + entry.reason = *reason; + for (const auto &dependency : *dependencies) { + const auto value = text(&dependency, limits.pathBytes); + if (!value) + return SnapshotStatus::corrupt; + entry.dependencies.push_back(*value); + } + for (const auto &source : *sources) { + const auto *fields_source = P::as_object(&source); + if (!fields_source) + return SnapshotStatus::corrupt; + const auto source_path = text(P::find_member(*fields_source, "path"), limits.pathBytes); + const auto content = text(P::find_member(*fields_source, "content"), limits.nameBytes); + if (!source_path || !content) + return SnapshotStatus::corrupt; + entry.sources.emplace(*source_path, *content); + } + for (const auto &record : *records) { + auto parsed_record = read_record(record, limits); + if (!parsed_record) + return SnapshotStatus::corrupt; + entry.records.push_back(std::move(*parsed_record)); + } + total += entry.records.size(); + if (total > limits.records) + return SnapshotStatus::corrupt; + if (!out.contexts.emplace(*name, std::move(entry)).second) + return SnapshotStatus::corrupt; + } + for (const auto &item : *overlays) { + const auto *fields = P::as_object(&item); + if (!fields) + return SnapshotStatus::corrupt; + const auto path = text(P::find_member(*fields, "path"), limits.pathBytes); + const auto content = text(P::find_member(*fields, "content"), limits.nameBytes); + const auto *records = P::as_array(P::find_member(*fields, "records")); + if (!path || !content || !records || records->size() > limits.recordsPerContext) + return SnapshotStatus::corrupt; + OverlayEntry overlay; + overlay.content = *content; + for (const auto &record : *records) { + auto parsed_record = read_record(record, limits); + if (!parsed_record) + return SnapshotStatus::corrupt; + overlay.records.push_back(std::move(*parsed_record)); + } + total += overlay.records.size(); + if (total > limits.records || !out.overlays.emplace(*path, std::move(overlay)).second) + return SnapshotStatus::corrupt; + } + return SnapshotStatus::ok; +} + +std::optional read_snapshot(const std::filesystem::path &path, std::size_t limit) { + std::ifstream stream{path, std::ios::binary}; + if (!stream) + return std::nullopt; + std::string bytes; + char buffer[65536]; + while (stream) { + stream.read(buffer, sizeof buffer); + bytes.append(buffer, static_cast(stream.gcount())); + if (bytes.size() > limit) + return std::nullopt; + } + return stream.eof() ? std::optional{std::move(bytes)} : std::nullopt; +} +} // namespace + +struct SymbolIndex::State { + explicit State(Limits value) : limits(value) {} + Limits limits; + mutable std::mutex mutex; + std::map contexts; + std::map overlays; + std::uint64_t generation{}; + std::shared_ptr current; + + Coverage coverage_locked(const std::optional &filter) const { + Coverage result; + for (const auto &[name, entry] : contexts) { + if (filter && name != *filter) + continue; + result.indexed = true; + if (!entry.complete) + result.incomplete.push_back(name); + } + if (!filter && !overlays.empty()) + result.indexed = true; + result.complete = result.indexed && result.incomplete.empty(); + return result; + } + + std::vector + snapshot_locked(std::vector> &contexts_out) const { + std::vector records; + for (const auto &[name, entry] : contexts) { + records.insert(records.end(), entry.records.begin(), entry.records.end()); + contexts_out.emplace_back(name, Coverage{true, entry.complete, {}}); + } + for (const auto &[path, overlay] : overlays) + records.insert(records.end(), overlay.records.begin(), overlay.records.end()); + return records; + } + + void publish_locked() { + ++generation; + std::vector> contexts_out; + auto records = snapshot_locked(contexts_out); + current = std::shared_ptr( + new Generation{generation, std::move(records), std::move(contexts_out)}); + } +}; + +SymbolIndex::SymbolIndex(Limits limits) : state_(std::make_shared(limits)) {} +SymbolIndex::~SymbolIndex() = default; + +bool SymbolIndex::publish(const ContextInput &input) { + auto &state = *state_; + for (const auto &record : input.records) + if (!valid_record(record, state.limits)) + return false; + for (const auto &dependency : input.dependencies) + if (!plain(dependency, state.limits.pathBytes)) + return false; + for (const auto &[path, content] : input.sources) + if (!plain(path, state.limits.pathBytes) || !plain(content, state.limits.nameBytes)) + return false; + std::lock_guard lock{state.mutex}; + if (!plain(input.context, state.limits.nameBytes) || + input.records.size() > state.limits.recordsPerContext || + (!state.contexts.contains(input.context) && state.contexts.size() >= state.limits.contexts)) + return false; + std::size_t total = input.records.size(); + for (const auto &[name, entry] : state.contexts) + if (name != input.context) + total += entry.records.size(); + if (total > state.limits.records) + return false; + ContextEntry entry; + entry.dependencies = input.dependencies; + entry.records = input.records; + entry.complete = input.complete; + entry.reason = input.reason; + for (const auto &[path, content] : input.sources) + entry.sources.emplace(path, content); + state.contexts[input.context] = std::move(entry); + state.publish_locked(); + return true; +} + +bool SymbolIndex::remove(std::string_view context) { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + if (state.contexts.erase(std::string{context}) == 0) + return false; + state.publish_locked(); + return true; +} + +bool SymbolIndex::set_overlay(std::string path, std::string content, + std::vector records) { + auto &state = *state_; + if (!plain(path, state.limits.pathBytes) || !plain(content, state.limits.nameBytes) || + records.size() > state.limits.recordsPerContext) + return false; + for (const auto &record : records) + if (!valid_record(record, state.limits)) + return false; + std::lock_guard lock{state.mutex}; + state.overlays[std::move(path)] = OverlayEntry{std::move(content), std::move(records)}; + return true; +} + +bool SymbolIndex::clear_overlay(std::string_view path) { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + return state.overlays.erase(std::string{path}) != 0; +} + +std::size_t SymbolIndex::invalidate(std::string_view path, + const std::optional &content) { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + std::size_t affected{}; + for (auto &[name, entry] : state.contexts) { + const bool dependent = std::ranges::contains(entry.dependencies, path) || + entry.sources.contains(std::string{path}); + if (!dependent) + continue; + const auto source = entry.sources.find(std::string{path}); + if (content && source != entry.sources.end() && source->second == *content) + continue; + if (source != entry.sources.end()) + entry.sources.erase(source); + if (entry.complete) { + entry.complete = false; + entry.reason = "changed source"; + ++affected; + } + } + if (affected) + state.publish_locked(); + return affected; +} + +Result SymbolIndex::find(const Query &query) const { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + Result result; + result.coverage = state.coverage_locked(query.context); + std::set> seen; + auto consider = [&](const SymbolRecord &record) { + if (query.name.empty() && !query.substring) + return; + const bool matches = + query.substring ? record.name.contains(query.name) : record.name == query.name; + if (!matches) + return; + if (!seen.emplace(record.name, record.kind, record.location).second) + return; + result.symbols.push_back(record); + }; + std::set shadowed; + for (const auto &[path, overlay] : state.overlays) + shadowed.insert(path); + for (const auto &[name, entry] : state.contexts) { + if (query.context && name != *query.context) + continue; + for (const auto &record : entry.records) + if (!shadowed.contains(record.location.path)) + consider(record); + } + for (const auto &[path, overlay] : state.overlays) + for (const auto &record : overlay.records) + consider(record); + std::ranges::sort(result.symbols, [](const auto &left, const auto &right) { + return std::tie(left.name, left.location, left.kind) < + std::tie(right.name, right.location, right.kind); + }); + if (result.symbols.size() > query.limit) { + result.symbols.resize(query.limit); + result.truncated = true; + } + return result; +} + +Coverage SymbolIndex::coverage() const { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + return state.coverage_locked(std::nullopt); +} + +std::shared_ptr SymbolIndex::current() const { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + return state.current; +} + +std::uint64_t SymbolIndex::generation() const { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + return state.generation; +} + +std::size_t SymbolIndex::records() const { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + std::size_t total{}; + for (const auto &[name, entry] : state.contexts) + total += entry.records.size(); + for (const auto &[path, overlay] : state.overlays) + total += overlay.records.size(); + return total; +} + +const Limits &SymbolIndex::limits() const noexcept { return state_->limits; } + +bool SymbolIndex::save(const fs::path &path) const { + auto &state = *state_; + Json root; + { + std::lock_guard lock{state.mutex}; + Json::Array contexts; + for (const auto &[name, entry] : state.contexts) { + Json::Array dependencies, sources, records; + for (const auto &dependency : entry.dependencies) + dependencies.push_back(Json{dependency}); + for (const auto &[source, content] : entry.sources) + sources.push_back( + Json{Json::Object{{"path", Json{source}}, {"content", Json{content}}}}); + for (const auto &record : entry.records) + records.push_back(record_json(record)); + contexts.push_back(Json{Json::Object{{"context", Json{name}}, + {"complete", Json{entry.complete}}, + {"reason", Json{entry.reason}}, + {"dependencies", Json{std::move(dependencies)}}, + {"sources", Json{std::move(sources)}}, + {"records", Json{std::move(records)}}}}); + } + Json::Array overlays; + for (const auto &[path, overlay] : state.overlays) { + Json::Array records; + for (const auto &record : overlay.records) + records.push_back(record_json(record)); + overlays.push_back(Json{Json::Object{{"path", Json{path}}, + {"content", Json{overlay.content}}, + {"records", Json{std::move(records)}}}}); + } + root = Json{Json::Object{{"schema", Json{snapshot_schema}}, + {"backend", Json{std::string{backend_name}}}, + {"generation", Json{static_cast(state.generation)}}, + {"contexts", Json{std::move(contexts)}}, + {"overlays", Json{std::move(overlays)}}}}; + } + // The digest covers the canonical payload without itself, so a flipped + // byte in valid JSON is corruption rather than silently trusted data. + auto payload = P::serialize_json(root); + if (!payload) + return false; + const auto digest = digest_of(*payload); + if (digest.size() != 64) + return false; + std::get(root.value).emplace("digest", Json{digest}); + auto serialized = P::serialize_json(root); + if (!serialized || serialized->size() > state.limits.snapshotBytes) + return false; + const auto temporary = path.parent_path() / (path.filename().native() + ".tmp"); + try { + fs::create_directories(path.parent_path()); + std::ofstream stream{temporary, std::ios::binary | std::ios::trunc}; + stream.write(serialized->data(), static_cast(serialized->size())); + stream.close(); + if (!stream) + return false; + const int descriptor = ::open(temporary.c_str(), O_RDONLY | O_CLOEXEC); + if (descriptor < 0 || ::fsync(descriptor) != 0) { + if (descriptor >= 0) + ::close(descriptor); + return false; + } + ::close(descriptor); + fs::rename(temporary, path); + return true; + } catch (const std::exception &) { + std::error_code error; + fs::remove(temporary, error); + return false; + } +} + +std::expected SymbolIndex::restore(const fs::path &path) { + std::error_code error; + if (!fs::exists(path, error)) + return LoadResult{LoadStatus::missing, generation(), std::nullopt, false}; + ParsedSnapshot parsed; + auto bytes = read_snapshot(path, limits().snapshotBytes + 1); + auto status = bytes ? parse_snapshot(*bytes, limits(), parsed) : SnapshotStatus::corrupt; + if (!bytes && fs::file_size(path, error) > limits().snapshotBytes) + status = SnapshotStatus::oversized; + if (status == SnapshotStatus::ok) { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + state.contexts = std::move(parsed.contexts); + state.overlays = std::move(parsed.overlays); + state.generation = parsed.generation; + state.publish_locked(); + return LoadResult{LoadStatus::loaded, state.generation, std::nullopt, parsed.migrated}; + } + static std::atomic quarantined{}; + const auto target = path.parent_path() / + (path.filename().native() + ".quarantine-" + std::to_string(::getpid()) + + "-" + std::to_string(quarantined.fetch_add(1))); + fs::rename(path, target, error); + if (error) + return std::unexpected("cannot quarantine the rejected index snapshot"); + auto &state = *state_; + std::lock_guard lock{state.mutex}; + state.contexts.clear(); + state.overlays.clear(); + state.publish_locked(); + const auto result = status == SnapshotStatus::incompatible ? LoadStatus::incompatible + : status == SnapshotStatus::oversized ? LoadStatus::oversized + : LoadStatus::corrupt; + return LoadResult{result, state.generation, target, false}; +} + +bool SymbolIndex::save_generation(const fs::path &root) { + std::error_code error; + fs::create_directories(root, error); + if (error) + return false; + const auto current = root / "snapshot.json"; + const auto previous = root / "snapshot.prev.json"; + if (fs::exists(current, error)) + fs::rename(current, previous, error); + if (!save(current)) + return false; + const auto temporary = root / "CURRENT.tmp"; + { + std::ofstream stream{temporary, std::ios::binary | std::ios::trunc}; + stream << "{\"schema\":2,\"file\":\"snapshot.json\"}\n"; + } + fs::rename(temporary, root / "CURRENT", error); + return !error; +} + +std::expected +SymbolIndex::restore_generation(const fs::path &root) { + std::error_code error; + if (!fs::exists(root, error)) + return LoadResult{LoadStatus::missing, generation(), std::nullopt}; + const auto current = root / "CURRENT"; + const auto legacy = root / "index.json"; + fs::path selected; + bool migrate_selector{}; + if (fs::exists(current, error)) { + std::ifstream stream{current, std::ios::binary}; + std::string line(256, '\0'); + stream.read(line.data(), static_cast(line.size())); + line.resize(static_cast(stream.gcount())); + while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) + line.pop_back(); + std::string file; + if (line == "snapshot.json") { + // Schema 1 selector: a bare file name. + file = line; + migrate_selector = true; + } else { + auto parsed = P::parse_json(line, max_json_depth); + const auto *fields = parsed ? P::as_object(&*parsed) : nullptr; + const auto *schema = fields ? P::find_member(*fields, "schema") : nullptr; + const auto *name = fields ? P::as_string(P::find_member(*fields, "file")) : nullptr; + const auto *value = schema ? std::get_if(&schema->value) : nullptr; + if (!fields || !name || !value || *value != 2) + return std::unexpected("unsupported index generation selector"); + file = *name; + } + if (file != "snapshot.json") + return std::unexpected("unsupported index generation selector"); + selected = root / file; + } else if (fs::exists(legacy, error)) { + selected = legacy; + } else { + return LoadResult{LoadStatus::missing, generation(), std::nullopt}; + } + auto result = restore(selected); + if (!result) + return result; + if (result->status != LoadStatus::loaded) { + const auto previous = root / "snapshot.prev.json"; + if (fs::exists(previous, error)) { + result = restore(previous); + // Keep CURRENT consistent: the recovered generation becomes current. + if (result && result->status == LoadStatus::loaded) + fs::copy_file(previous, root / "snapshot.json", + fs::copy_options::overwrite_existing, error); + } + } + if (result && result->status == LoadStatus::loaded && (migrate_selector || result->migrated)) { + const auto temporary = root / "CURRENT.tmp"; + std::ofstream stream{temporary, std::ios::binary | std::ios::trunc}; + stream << "{\"schema\":2,\"file\":\"snapshot.json\"}\n"; + stream.close(); + fs::rename(temporary, current, error); + // Persist the upgraded snapshot format; the previous generation is + // kept as snapshot.prev.json for crash recovery. + if (!save_generation(root)) + return std::unexpected("cannot persist the migrated index generation"); + } + if (result && result->status == LoadStatus::loaded && !fs::exists(current, error)) + static_cast(save_generation(root)); + return result; +} + +bool SymbolIndex::load(const fs::path &path) { + auto bytes = read_snapshot(path, limits().snapshotBytes); + if (!bytes) + return false; + ParsedSnapshot parsed; + if (parse_snapshot(*bytes, limits(), parsed) != SnapshotStatus::ok) + return false; + auto &state = *state_; + std::lock_guard lock{state.mutex}; + state.contexts = std::move(parsed.contexts); + state.overlays = std::move(parsed.overlays); + state.generation = parsed.generation; + state.publish_locked(); + return true; +} + +} // namespace vls::index diff --git a/src/main.cpp b/src/main.cpp index 856f6ba..06d823a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,27 +1,150 @@ #include +#include #include #include +#include #include +#include #include +namespace { +namespace fs = std::filesystem; +namespace Workspace = Void::LanguageServer::Workspace; + +struct Options { + std::optional root, user_file, provider, database, selector, build_root, + producer_cwd, profile, gcc_profile; + bool gcc_diagnostics{}; +}; + +std::expected workspace_launch(const Options &options) { + vls::WorkspaceLaunch launch; + if (!options.root) { + if (options.user_file || options.provider || options.database || options.selector || + options.build_root || options.producer_cwd || options.profile || + options.gcc_profile || options.gcc_diagnostics) + return std::unexpected{"workspace options require --workspace-root"}; + return launch; + } + const fs::path root{*options.root}; + std::error_code ec; + if (!root.is_absolute() || !fs::is_directory(root, ec)) + return std::unexpected{"--workspace-root requires an existing absolute directory"}; + launch.root = fs::canonical(root, ec); + if (ec) + return std::unexpected{"could not resolve the selected workspace"}; + if (options.user_file) { + auto user = Workspace::read_user_settings(*options.user_file); + if (!user) + return std::unexpected{user.error().message}; + launch.user_settings = std::move(*user); + } + auto directory = [](const std::optional &value) + -> std::expected, std::string> { + if (!value) + return std::nullopt; + const fs::path path{*value}; + std::error_code error; + if (!path.is_absolute() || path != path.lexically_normal() || + !fs::is_directory(path, error)) + return std::unexpected{ + "VBS directory options require an existing normalized absolute directory"}; + return path; + }; + auto build = directory(options.build_root), producer = directory(options.producer_cwd); + if (!build || !producer) + return std::unexpected{!build ? build.error() : producer.error()}; + launch.build_root = std::move(*build); + launch.producer_cwd = std::move(*producer); + Workspace::SettingsOverrides overrides; + overrides.compdb_path = options.database; + overrides.vbs_manifest_path = options.selector; + overrides.selected_profile = options.profile; + if (options.gcc_profile && options.gcc_diagnostics) + return std::unexpected{"choose either --gcc-profile or --gcc-diagnostics"}; + // D-031: diagnostics are prepared in process by default for a selected + // workspace. An explicit flag fails loudly; the default falls back to a + // passive session when the local toolchain is unavailable. + const bool diagnostics_default = + !options.gcc_profile && (!options.provider || *options.provider != "none"); + if (options.gcc_profile || options.gcc_diagnostics || diagnostics_default) { + auto profile = options.gcc_profile + ? vls::semantic::GccProfile::load(*options.gcc_profile) + : vls::semantic::GccProfile::prepare("g++"); + if (!profile) { + if (options.gcc_profile || options.gcc_diagnostics) + return std::unexpected{profile.error()}; + } else { + launch.diagnostics_profile = std::move(*profile); + } + if (launch.diagnostics_profile) + overrides.tool_approvals = {{*launch.root, Workspace::AuthorityLevel::compiler_use, + launch.diagnostics_profile->driver}}; + } + if (options.provider) { + for (auto choice : + {Workspace::ProviderPreference::auto_detect, Workspace::ProviderPreference::vbs, + Workspace::ProviderPreference::compdb, Workspace::ProviderPreference::none}) { + if (*options.provider == Workspace::provider_preference_name(choice)) + overrides.provider = choice; + } + if (!overrides.provider) + return std::unexpected{"--provider expects auto, vbs, compdb or none"}; + } + auto cli = Workspace::settings_from_cli(std::move(overrides), *launch.root); + if (!cli.diagnostics().empty()) + return std::unexpected{cli.diagnostics().front().message}; + launch.cli_settings = std::move(cli); + return launch; +} +} // namespace + int main(int argc, char **argv) { bool stdio = false; bool version = false; + Options options; Void::Argparse::Parser parser{ - "vls", "VoidLanguageServer 0.1.0: stdio LSP lifecycle shell.\n" - "No arguments starts stdio. Language and debugger features are planned."}; - parser.flag("--stdio", "", "run the stdio LSP lifecycle shell", stdio); + "vls", "VoidLanguageServer provides C++26 language services for Void projects.\n" + "With no arguments, VLS serves LSP over standard input and output."}; + parser.flag("--stdio", "", "run the language server over standard input and output", stdio); parser.flag("--version", "-V", "show version", version); + parser.option("--workspace-root", "", "workspace for these launcher settings", options.root); + parser.option("--user-config", "", "absolute user settings file for this workspace", + options.user_file); + parser.option("--provider", "", "auto, vbs, compdb or none", options.provider); + parser.option("--compdb", "", "compilation database locator", options.database); + parser.option("--vbs-manifest", "", "VBS editor selection record", options.selector); + parser.option("--vbs-build-root", "", "absolute directory containing VBS profiles", + options.build_root); + parser.option("--vbs-producer-cwd", "", "working directory used to publish relative VBS paths", + options.producer_cwd); + parser.option("--profile", "", "preferred build context profile", options.profile); + parser.option( + "--gcc-profile", "", + "enable stock GCC diagnostics for this workspace using an absolute prepared profile", + options.gcc_profile); + parser.flag("--gcc-diagnostics", "", + "prepare stock GCC diagnostics in process from the selected GCC driver " + "(enabled by default when a workspace is selected)", + options.gcc_diagnostics); if (argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h")) { std::cout << parser.help(); return std::cout ? 0 : 1; } - // Each mode is standalone. This also rejects duplicate flags deterministically. - if (argc > 2) { - std::cerr << "vls: options must be used alone; use --help\n"; - return 2; + std::set seen; + for (int i = 1; i < argc; ++i) { + const std::string_view arg = argv[i]; + if (!arg.starts_with('-')) + continue; + const auto name = arg.substr(0, arg.find('=')); + if (arg == "--" || !seen.insert(name).second || + (argc != 2 && + (name == "--help" || name == "-h" || name == "--version" || name == "-V"))) { + std::cerr << "vls: invalid option combination; use --help\n"; + return 2; + } } const auto parsed = parser.parse(argc, argv); if (!parsed) { @@ -32,8 +155,13 @@ int main(int argc, char **argv) { std::cout << "VoidLanguageServer " << vls::server_version << '\n'; return std::cout ? 0 : 1; } + auto launch = workspace_launch(options); + if (!launch) { + std::cerr << "vls: " << launch.error() << '\n'; + return 2; + } #ifdef SIGPIPE std::signal(SIGPIPE, SIG_IGN); #endif - return vls::run_stdio(std::cin, std::cout, std::cerr); + return vls::run_stdio(std::cin, std::cout, std::cerr, {}, std::move(*launch)); } diff --git a/src/modules/ArtifactCache.cpp b/src/modules/ArtifactCache.cpp new file mode 100644 index 0000000..1496929 --- /dev/null +++ b/src/modules/ArtifactCache.cpp @@ -0,0 +1,328 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::modules { +namespace fs = std::filesystem; + +namespace { +constexpr std::size_t max_artifact_bytes = 512 * 1024 * 1024; +constexpr std::size_t max_manifest_bytes = 16 * 1024 * 1024; + +std::string hex(std::string_view bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string text; + text.reserve(bytes.size() * 2); + for (const unsigned char byte : bytes) { + text += digits[byte >> 4]; + text += digits[byte & 0xf]; + } + return text; +} + +std::string unhex(std::string_view text, std::size_t limit) { + if (text.size() % 2 || text.size() > limit * 2) + throw std::runtime_error("invalid artifact manifest field"); + auto value = [](char c) -> int { + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + return -1; + }; + std::string bytes; + bytes.reserve(text.size() / 2); + for (std::size_t i = 0; i < text.size(); i += 2) { + const int high = value(text[i]), low = value(text[i + 1]); + if (high < 0 || low < 0) + throw std::runtime_error("invalid artifact manifest field"); + bytes += static_cast((high << 4) | low); + } + return bytes; +} + +bool digest_text(std::string_view text) { + return text.size() == 64 && std::ranges::all_of(text, [](char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + }); +} + +std::string digest(std::string_view bytes) { + auto value = Void::Crypto::sha256(bytes); + if (!value) + throw std::runtime_error("could not hash an artifact"); + return Void::Encoding::Hex::encode(*value); +} + +std::string read_file(const fs::path &path, std::size_t limit) { + std::ifstream stream{path, std::ios::binary}; + if (!stream) + throw std::runtime_error("cannot open " + path.native()); + std::string bytes; + char buffer[65536]; + while (stream) { + stream.read(buffer, sizeof buffer); + bytes.append(buffer, static_cast(stream.gcount())); + if (bytes.size() > limit) + throw std::runtime_error("artifact exceeds its size limit"); + } + if (!stream.eof()) + throw std::runtime_error("cannot read " + path.native()); + return bytes; +} + +void write_file(const fs::path &path, std::string_view bytes) { + std::ofstream stream{path, std::ios::binary | std::ios::trunc}; + stream.write(bytes.data(), static_cast(bytes.size())); + stream.flush(); + if (!stream) + throw std::runtime_error("cannot write " + path.native()); + stream.close(); + const int descriptor = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (descriptor < 0 || ::fsync(descriptor) != 0) { + if (descriptor >= 0) + ::close(descriptor); + throw std::runtime_error("cannot sync " + path.native()); + } + ::close(descriptor); +} + +void sync_directory(const fs::path &path) { + const int descriptor = ::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (descriptor < 0) + throw std::runtime_error("cannot open a cache directory"); + const bool ok = ::fsync(descriptor) == 0; + ::close(descriptor); + if (!ok) + throw std::runtime_error("cannot sync a cache directory"); +} + +std::string unique_name() { + static std::atomic sequence{}; + return std::to_string(::getpid()) + "-" + std::to_string(sequence.fetch_add(1)); +} + +struct Cleanup { + fs::path path; + bool armed{true}; + ~Cleanup() { + if (armed) { + std::error_code error; + fs::remove_all(path, error); + } + } +}; +} // namespace + +std::string ArtifactKey::identity() const { + return digest(compatibility + '\0' + context + '\0' + inputs + '\0' + kind); +} + +std::optional ArtifactGeneration::find(const ArtifactKey &key) const { + const auto entry = entries_.find(key); + if (entry == entries_.end()) + return std::nullopt; + return entry->second; +} + +struct ArtifactCache::State { + State(fs::path cache, std::size_t keep) : root(std::move(cache)), retained(keep) {} + fs::path root; + std::size_t retained; + mutable std::mutex mutex; + std::shared_ptr current; + std::map> known; + std::deque order; +}; + +ArtifactCache::ArtifactCache(fs::path root, std::size_t retained) + : state_(std::make_shared(std::move(root), retained)) {} +ArtifactCache::~ArtifactCache() = default; + +std::expected, std::string> +ArtifactCache::publish(const std::map &artifacts) { + try { + if (artifacts.empty()) + return std::unexpected("no artifacts to publish"); + auto &state = *state_; + fs::create_directories(state.root / "generations"); + fs::create_directories(state.root / "tmp"); + const auto temporary = state.root / "tmp" / unique_name(); + fs::create_directory(temporary); + Cleanup cleanup{temporary}; + std::map contents; + std::map digests; + for (const auto &[key, path] : artifacts) { + auto bytes = read_file(path, max_artifact_bytes); + const auto sha = digest(bytes); + contents.emplace(sha, std::move(bytes)); + digests.emplace(key, sha); + } + std::string manifest; + for (const auto &[key, sha] : digests) + manifest += hex(key.compatibility) + " " + hex(key.context) + " " + hex(key.inputs) + + " " + hex(key.kind) + " " + sha + " " + sha + "\n"; + const auto id = digest(manifest); + const auto target = state.root / "generations" / id; + if (!fs::exists(target)) { + for (const auto &[sha, bytes] : contents) + write_file(temporary / sha, bytes); + write_file(temporary / "manifest", manifest); + sync_directory(temporary); + fs::rename(temporary, target); + cleanup.armed = false; + sync_directory(state.root / "generations"); + } + std::map entries; + for (const auto &line : + read_file(target / "manifest", max_manifest_bytes) | std::views::split('\n')) { + std::string_view text{line.begin(), line.end()}; + if (text.empty()) + continue; + std::array fields; + std::size_t field{}; + while (!text.empty() && field != fields.size()) { + const auto space = text.find(' '); + fields[field++] = text.substr(0, space); + text = + space == std::string_view::npos ? std::string_view{} : text.substr(space + 1); + } + if (field != fields.size() || !text.empty()) + throw std::runtime_error("invalid artifact manifest"); + ArtifactKey key{unhex(fields[0], 4096), unhex(fields[1], 4096), unhex(fields[2], 4096), + unhex(fields[3], 256)}; + const auto sha = std::string{fields[4]}; + const auto name = std::string{fields[5]}; + if (!digest_text(sha) || name != sha || !fs::is_regular_file(target / name)) + throw std::runtime_error("invalid artifact manifest entry"); + entries.emplace(key, ArtifactEntry{key, target / name, sha}); + } + if (entries.size() != digests.size()) + throw std::runtime_error("incomplete artifact manifest"); + auto generation = std::shared_ptr( + new ArtifactGeneration{id, target, std::move(entries)}); + { + std::lock_guard lock{state.mutex}; + state.current = generation; + state.known[id] = generation; + state.order.push_back(id); + while (state.order.size() > 256) + state.order.pop_front(); + } + return generation; + } catch (const std::exception &error) { + return std::unexpected(error.what()); + } +} + +std::shared_ptr ArtifactCache::current() const { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + return state.current; +} + +std::size_t ArtifactCache::collect() { + auto &state = *state_; + std::vector remove; + { + std::lock_guard lock{state.mutex}; + std::set keep; + if (state.current) + keep.insert(state.current->id()); + std::size_t retained{}; + for (auto entry = state.order.rbegin(); entry != state.order.rend(); ++entry) { + const auto known = state.known.find(*entry); + if (known == state.known.end()) + continue; + if (known->second.lock() || retained < state.retained) { + keep.insert(*entry); + if (!known->second.lock()) + ++retained; + } + } + for (auto entry = state.known.begin(); entry != state.known.end();) { + if (keep.contains(entry->first)) { + ++entry; + continue; + } + remove.push_back(state.root / "generations" / entry->first); + entry = state.known.erase(entry); + } + std::erase_if(state.order, [&](const auto &id) { return !state.known.contains(id); }); + } + std::size_t removed{}; + for (const auto &path : remove) { + std::error_code error; + removed += fs::remove_all(path, error); + } + return removed; +} + +std::size_t ArtifactCache::generations() const { + auto &state = *state_; + std::lock_guard lock{state.mutex}; + std::error_code error; + std::size_t count{}; + for (const auto &entry : fs::directory_iterator{state.root / "generations", error}) + if (entry.is_directory()) + ++count; + return count; +} + +std::expected, std::string> +produce_module_artifacts(const ModulePlan &plan, ArtifactCache &cache, const fs::path &staging, + ArtifactWork work, std::stop_token stop) { + try { + if (!plan.ready()) + return std::unexpected("module plan is not ready"); + if (!work) + return std::unexpected("no artifact work"); + std::error_code error; + fs::remove_all(staging, error); + fs::create_directories(staging); + Cleanup cleanup{staging}; + std::map artifacts; + for (const auto &key : plan.order) { + if (stop.stop_requested()) + return std::unexpected("artifact production cancelled"); + const auto unit = std::ranges::find_if(plan.units, [&](const auto &candidate) { + return candidate.member.context.alternative == key.alternative; + }); + if (unit == plan.units.end()) + return std::unexpected("planned unit is missing from the census"); + const auto output = staging / hex(key.alternative); + auto produced = work(stop, key, output); + if (!produced) + return std::unexpected(produced.error()); + if (stop.stop_requested()) + return std::unexpected("artifact production cancelled"); + if (!fs::is_regular_file(*produced)) + return std::unexpected("artifact work produced no regular file"); + const auto &inputs = unit->member.inputs; + ArtifactKey artifact{plan.domain.compatibility, key.alternative, + inputs.command + "|" + inputs.source + "|" + + inputs.textual_closure + "|" + + inputs.system_closure.value_or(""), + "cmi"}; + artifacts.emplace(std::move(artifact), *produced); + } + return cache.publish(artifacts); + } catch (const std::exception &error) { + return std::unexpected(error.what()); + } +} + +} // namespace vls::modules diff --git a/src/modules/GccArtifacts.cpp b/src/modules/GccArtifacts.cpp new file mode 100644 index 0000000..bd34895 --- /dev/null +++ b/src/modules/GccArtifacts.cpp @@ -0,0 +1,119 @@ +#include + +#include + +#include +#include +#include +#include +#include + +namespace vls::modules { +namespace fs = std::filesystem; +namespace { +constexpr std::size_t max_cache_entries = 4096; +constexpr unsigned max_cache_depth = 8; +constexpr std::size_t max_error_bytes = 1024 * 1024; + +std::string unique_name() { + static std::atomic sequence{}; + return std::to_string(::getpid()) + "-" + std::to_string(sequence.fetch_add(1)); +} + +struct Cleanup { + fs::path path; + ~Cleanup() { + std::error_code error; + fs::remove_all(path, error); + } +}; + +void copy_artifact(const fs::path &from, const fs::path &to) { + std::ifstream input{from, std::ios::binary}; + if (!input) + throw std::runtime_error("cannot open the produced module artifact"); + fs::create_directories(to.parent_path()); + std::ofstream output{to, std::ios::binary | std::ios::trunc}; + if (!output) + throw std::runtime_error("cannot create the private module artifact"); + output << input.rdbuf(); + output.close(); + if (!output) + throw std::runtime_error("cannot write the private module artifact"); +} + +void collect(const fs::path &directory, unsigned depth, std::vector &found) { + if (depth > max_cache_depth || found.size() > max_cache_entries) + throw std::runtime_error("module cache exceeds its bounds"); + std::error_code error; + for (const auto &entry : fs::directory_iterator{directory, error}) { + if (error) + throw std::runtime_error("cannot read the module cache"); + if (entry.is_directory()) { + collect(entry.path(), depth + 1, found); + } else if (entry.is_regular_file() && entry.path().extension() == ".gcm") { + found.push_back(entry.path()); + if (found.size() > max_cache_entries) + throw std::runtime_error("module cache exceeds its bounds"); + } + } +} +} // namespace + +ArtifactWork gcc_module_artifact_work(ModuleCommandLookup lookup, GccArtifactOptions options) { + return [lookup = std::move(lookup), + options](std::stop_token stop, const Build::ContextKey &context, + const fs::path &output) -> std::expected { + try { + if (!lookup) + return std::unexpected("no module command lookup"); + const auto command = lookup(context); + if (!command || command->arguments.empty()) + return std::unexpected("no checked module command for the planned unit"); + if (!command->working_directory.is_absolute()) + return std::unexpected("module command working directory must be absolute"); + const auto work = output.parent_path() / ("module-" + unique_name()); + fs::create_directories(work); + Cleanup cleanup{work}; + Void::Process::SpawnOptions spawn; + spawn.executable = command->arguments.front(); + spawn.arguments.assign(command->arguments.begin() + 1, command->arguments.end()); + spawn.working_directory = work; + spawn.search_path = false; + spawn.environment.set_vars = {{"LC_ALL", "C"}}; + auto child = Void::Process::spawn(spawn); + if (!child) + return std::unexpected("could not start the module compiler"); + auto received = + Void::Process::communicate_blocking(*child, {}, + {.max_stdout_bytes = options.max_output_bytes, + .max_stderr_bytes = max_error_bytes, + .max_line_bytes = max_error_bytes}, + options.deadline, stop); + if (!received) + return std::unexpected("module compiler communication failed"); + if (received->cancelled || stop.stop_requested()) + return std::unexpected("module compilation cancelled"); + if (received->timed_out) + return std::unexpected("module compilation timed out"); + if (!received->status.exited || received->status.code != 0) + return std::unexpected("module compiler failed: " + received->err.substr(0, 512)); + std::vector artifacts; + const auto cache = work / "gcm.cache"; + std::error_code error; + if (fs::is_directory(cache, error)) + collect(cache, 0, artifacts); + if (artifacts.size() != 1) + return std::unexpected("expected exactly one module interface artifact"); + const auto size = fs::file_size(artifacts.front(), error); + if (error || size == 0 || size > options.max_artifact_bytes) + return std::unexpected("module interface artifact has an invalid size"); + copy_artifact(artifacts.front(), output); + return output; + } catch (const std::exception &error) { + return std::unexpected(error.what()); + } + }; +} + +} // namespace vls::modules diff --git a/src/modules/GccScan.cpp b/src/modules/GccScan.cpp new file mode 100644 index 0000000..b5016cc --- /dev/null +++ b/src/modules/GccScan.cpp @@ -0,0 +1,121 @@ +#include + +#include + +#include +#include +#include +#include +#include + +namespace vls::modules { +namespace fs = std::filesystem; +namespace { +constexpr std::size_t max_error_bytes = 1024 * 1024; + +std::string unique_name() { + static std::atomic sequence{}; + return std::to_string(::getpid()) + "-" + std::to_string(sequence.fetch_add(1)); +} + +struct Cleanup { + fs::path path; + ~Cleanup() { + std::error_code error; + fs::remove_all(path, error); + } +}; + +std::string read_file(const fs::path &path, std::size_t limit) { + std::ifstream stream{path, std::ios::binary}; + if (!stream) + throw std::runtime_error("cannot open the scan dependency file"); + std::string bytes; + char buffer[65536]; + while (stream) { + stream.read(buffer, sizeof buffer); + bytes.append(buffer, static_cast(stream.gcount())); + if (bytes.size() > limit) + throw std::runtime_error("scan dependency file exceeds its limit"); + } + if (!stream.eof()) + throw std::runtime_error("cannot read the scan dependency file"); + return bytes; +} +} // namespace + +std::function +gcc_module_scan_work(ScanCommandLookup lookup, Build::ContextKey context, + std::shared_ptr product, ScanOptions options) { + return [lookup = std::move(lookup), context = std::move(context), product, + options](std::stop_token stop) -> std::string { + if (!product) + throw std::runtime_error("no scan product owner"); + if (!lookup) + throw std::runtime_error("no scan command lookup"); + const auto command = lookup(context); + if (!command || command->arguments.empty()) + throw std::runtime_error("no checked scan command for the planned unit"); + if (!command->working_directory.is_absolute() || !options.directory.is_absolute()) + throw std::runtime_error("scan paths must be absolute"); + std::vector arguments = command->arguments; + std::optional dependency; + for (const auto &argument : arguments) { + if (!argument.starts_with("-fdeps-file=")) + continue; + if (dependency) + throw std::runtime_error("duplicate scan dependency file"); + const fs::path value = argument.substr(std::string_view{"-fdeps-file="}.size()); + if (!value.is_absolute()) + throw std::runtime_error("scan dependency file must be absolute"); + dependency = value; + } + if (!dependency) + throw std::runtime_error("scan command has no dependency file"); + std::error_code error; + fs::create_directories(options.directory, error); + if (error) + throw std::runtime_error("cannot create the private scan directory"); + const auto directory = options.directory / ("scan-" + unique_name()); + fs::create_directory(directory, error); + if (error) + throw std::runtime_error("cannot create the private scan directory"); + Cleanup cleanup{directory}; + const auto selected = directory / "deps.json"; + for (auto &argument : arguments) + if (argument.starts_with("-fdeps-file=")) + argument = "-fdeps-file=" + selected.native(); + + Void::Process::SpawnOptions spawn; + spawn.executable = arguments.front(); + spawn.arguments.assign(arguments.begin() + 1, arguments.end()); + spawn.working_directory = command->working_directory; + spawn.search_path = false; + spawn.environment.set_vars = {{"LC_ALL", "C"}}; + auto child = Void::Process::spawn(spawn); + if (!child) + throw std::runtime_error("could not start the module scanner"); + auto received = Void::Process::communicate_blocking(*child, {}, + {.max_stdout_bytes = options.max_bytes, + .max_stderr_bytes = max_error_bytes, + .max_line_bytes = max_error_bytes}, + options.deadline, stop); + if (!received) + throw std::runtime_error("module scanner communication failed"); + if (received->cancelled || stop.stop_requested()) + throw std::runtime_error("module scan cancelled"); + if (received->timed_out) + throw std::runtime_error("module scan timed out"); + if (!received->status.exited || received->status.code != 0) + throw std::runtime_error("module scanner failed: " + received->err.substr(0, 512)); + auto bytes = read_file(selected, options.max_bytes); + auto decoded = decode_scan(bytes, command->output); + if (!decoded) + throw std::runtime_error("module scan rule could not be verified"); + product->p1689 = std::move(bytes); + product->rule = std::move(*decoded); + return command->output.spelling; + }; +} + +} // namespace vls::modules diff --git a/src/modules/ModuleGraph.cpp b/src/modules/ModuleGraph.cpp new file mode 100644 index 0000000..b496cb5 --- /dev/null +++ b/src/modules/ModuleGraph.cpp @@ -0,0 +1,672 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace vls::modules { +namespace { + +namespace P = Void::LanguageServer::Protocol; +using Object = P::Json::Object; + +bool identifier(std::string_view value) { return !value.empty() && value.find('\0') == value.npos; } + +bool valid_output(const ExpectedOutput &output) { + return output.working_directory.is_absolute() && + !output.working_directory.native().contains(std::filesystem::path::value_type{}) && + identifier(output.spelling); +} + +// The helpers unwind only a typed wire error; the public decoder returns an expected. +const Object &object(const P::Json &value) { + if (const auto *fields = P::as_object(&value)) + return *fields; + throw ScanError::invalid_shape; +} + +// The parser first bounds raw bytes and nesting. Bound the decoded tree, including ignored +// vendor extensions, before constructing indices or copying module descriptions. +void check_tree(const P::Json &value, std::size_t &remaining) { + if (remaining == 0) + throw ScanError::limit; + --remaining; + if (const auto *string = P::as_string(&value)) { + if (string->size() > max_field_bytes) + throw ScanError::limit; + } else if (const auto *items = P::as_array(&value)) { + if (items->size() > max_rule_items) + throw ScanError::limit; + for (const auto &item : *items) + check_tree(item, remaining); + } else if (const auto *fields = P::as_object(&value)) { + if (fields->size() > max_rule_items) + throw ScanError::limit; + for (const auto &[key, item] : *fields) { + if (key.size() > max_field_bytes) + throw ScanError::limit; + check_tree(item, remaining); + } + } +} + +void check_fields(const Object &fields, std::initializer_list allowed) { + for (const auto &[key, value] : fields) { + if (!key.starts_with('_') && !std::ranges::contains(allowed, key)) + throw ScanError::unsupported_field; + } +} + +std::string_view text_field(const P::Json *field) { + const auto *value = P::as_string(field); + if (!value) + throw ScanError::invalid_shape; + if (!identifier(*value)) + throw ScanError::invalid_shape; + return *value; +} + +std::optional optional_text(const Object &entry, std::string_view key) { + if (const auto *field = P::find_member(entry, key)) + return std::string(text_field(field)); + return {}; +} + +bool bool_field(const Object &entry, std::string_view key, bool fallback) { + const auto *field = P::find_member(entry, key); + if (!field) + return fallback; + if (const auto flag = P::as_bool(field)) + return *flag; + throw ScanError::invalid_shape; +} + +void zero_version(const Object &fields, std::string_view key, bool required) { + const auto *field = P::find_member(fields, key); + if (!field && !required) + return; + const auto *number = field ? std::get_if(&field->value) : nullptr; + if (!number) + throw ScanError::invalid_shape; + if (*number != 0) + throw ScanError::unsupported_version; +} + +std::span array_field(const Object &fields, std::string_view key) { + const auto *value = P::find_member(fields, key); + if (!value) + return {}; + const auto *items = P::as_array(value); + if (!items) + throw ScanError::invalid_shape; + return *items; +} + +template std::vector descriptions(std::span array) { + std::vector result; + result.reserve(array.size()); + for (const auto &item : array) { + const auto &fields = object(item); + constexpr bool providing = std::is_same_v; + check_fields(fields, + {"logical-name", "unique-on-source-path", "source-path", + "compiled-module-path", providing ? "is-interface" : "lookup-method"}); + Entry entry; + entry.logical_name = text_field(P::find_member(fields, "logical-name")); + entry.source_path = optional_text(fields, "source-path"); + entry.compiled_module_path = optional_text(fields, "compiled-module-path"); + entry.unique_on_source_path = bool_field(fields, "unique-on-source-path", false); + if (entry.unique_on_source_path && !entry.source_path) + throw ScanError::invalid_shape; + if constexpr (providing) { + entry.is_interface = bool_field(fields, "is-interface", true); + } else if (const auto *field = P::find_member(fields, "lookup-method")) { + const auto method = text_field(field); + if (method == "include-angle") + entry.lookup = LookupMethod::include_angle; + else if (method == "include-quote") + entry.lookup = LookupMethod::include_quote; + else if (method != "by-name") + throw ScanError::unsupported_field; + } + result.push_back(std::move(entry)); + } + // Keep scanner order for external occurrence bindings. Compare through indices. + std::set seen; + for (const auto &entry : result) + if (!seen.insert(&entry).second) + throw ScanError::invalid_shape; + return result; +} + +// Keep non-ASCII bytes of the compiler's UTF-8 name opaque. This check excludes path-like +// spellings from named lookup. The owner separately certifies all header provisions and uses, +// including headers whose spelling could also be a valid module name. +bool named_module(std::string_view name) { + bool start = true, partition = false; + for (const unsigned char ch : name) { + if (ch == '.' || ch == ':') { + if (start || (ch == ':' && partition)) + return false; + partition |= ch == ':'; + start = true; + } else { + const bool name_byte = + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_' || ch >= 0x80; + if (!name_byte && (start || ch < '0' || ch > '9')) + return false; + start = false; + } + } + return !start; +} + +// Account caller-owned evidence before copying or indexing any of it. Wire objects have +// already passed the decoder's per-array and field bounds. +struct GraphLimit {}; +struct Budget { + std::size_t bytes{}, items{}; + void add_bytes(std::size_t n) { + if (n > max_graph_bytes - bytes) + throw GraphLimit{}; + bytes += n; + } + void add_items(std::size_t n) { + if (n > max_graph_items - items) + throw GraphLimit{}; + items += n; + } + void field(std::size_t n) { + if (n > max_field_bytes) + throw GraphLimit{}; + add_bytes(n); + } + void optional(const std::optional &value) { + if (value) + field(value->size()); + } + void domain(const ModuleDomain &value) { + field(value.compatibility.size()); + field(value.lookup.size()); + } + void context(const Build::ContextKey &key) { + optional(key.profile); + optional(key.target); + field(key.alternative.size()); + field(key.owning_tu.native().size()); + } + void inputs(const UnitInputs &value) { + field(value.command.size()); + field(value.source.size()); + field(value.textual_closure.size()); + optional(value.system_closure); + } + void member(const CensusMember &value) { + context(value.context); + inputs(value.inputs); + field(value.output.working_directory.native().size()); + field(value.output.spelling.size()); + field(value.scan_revision.size()); + if (const auto &header = value.staged_header) { + field(header->generation.size()); + field(header->source_identity.size()); + domain(header->domain); + context(header->producer); + inputs(header->inputs); + } + } + void scan(const ScanEvidence &value) { + domain(value.domain); + context(value.context); + inputs(value.inputs); + field(value.scan_revision.size()); + if (value.rule && *value.rule) { + const auto &rule = **value.rule; + add_bytes(rule.wire_bytes()); + add_items(rule.additional_outputs().size() + rule.provides().size() + + rule.requirements().size()); + } + if (value.provided_headers.size() > max_rule_items || + value.writers.size() > max_rule_items + 1 || + (value.header_uses && value.header_uses->size() > max_rule_items)) + throw GraphLimit{}; + add_items(value.provided_headers.size()); + add_items(value.writers.size()); + for (const auto &provision : value.provided_headers) + field(provision.source_identity.size()); + for (const auto &writer : value.writers) + field(writer.size()); + if (value.header_uses) { + add_items(value.header_uses->size()); + for (const auto &use : *value.header_uses) { + field(use.source_identity.size()); + optional(use.loaded_generation); + } + } + } +}; + +using Index = std::size_t; +using Context = Build::ContextKey; +using Claim = std::pair; // Resolved header identity, or named module. +struct Provider { + Index first; + bool ambiguous{}; +}; + +struct Node { + const ScanEvidence *scan{}; + bool foreign{}, duplicate{}; + std::vector provisions; + std::vector imports; + std::vector dependencies; + std::vector issues; +}; + +class Planner { + public: + ModulePlan plan; + + void collect(const ModuleCensus &, std::span, const Context &); + + private: + std::vector nodes_; + std::map providers_; + std::map writers_; + void block(PlanIssue code, std::optional unit = {}, std::string_view detail = {}, + std::optional error = {}) { + plan.blockers.push_back({code, unit, std::string(detail), error}); + } + void local(Index unit, PlanIssue issue, std::string_view detail) { + nodes_[unit].issues.push_back({issue, unit, std::string(detail), {}}); + } + void index_scan(Index); + void index_claims(Index, const ScanRule &); + void link_imports(Index); + void order_from(Index); +}; + +// Bind using the exact positions in this (owned, decoded) rule. Multiple spellings of one +// resolved header may occupy distinct positions, but a position may have only one binding. +template +bool bind_indices(const std::vector &bindings, std::vector &slots, + std::size_t count) { + slots.assign(count, nullptr); + for (const auto &entry : bindings) { + if (entry.index >= count || slots[entry.index] || !identifier(entry.source_identity)) + return false; + slots[entry.index] = &entry; + } + return true; +} + +void Planner::index_scan(Index i) { + const auto &member = plan.units[i].member; + const auto &node = nodes_[i]; + if (member.inputs.source.empty()) + block(PlanIssue::missing_source, i); + if (!identifier(member.inputs.source) || !identifier(member.inputs.command) || + !identifier(member.inputs.textual_closure) || !identifier(member.scan_revision) || + (member.inputs.system_closure && !identifier(*member.inputs.system_closure))) + block(PlanIssue::incomplete_inputs, i); + if (!node.scan) { + block(node.foreign ? PlanIssue::wrong_domain : PlanIssue::missing_scan, i); + return; + } + if (node.duplicate) { + block(PlanIssue::duplicate_scan, i); + return; + } + const auto &scan = *node.scan; + if (scan.inputs != member.inputs || scan.scan_revision != member.scan_revision) + block(PlanIssue::stale_scan, i); + if (!scan.exit_status) + block(PlanIssue::incomplete_scan, i, "unobserved compiler exit"); + else if (*scan.exit_status != 0) + block(PlanIssue::scan_failed, i); + if (!scan.rule) { + block(PlanIssue::missing_rule, i); + return; + } + if (!*scan.rule) { + block(PlanIssue::invalid_rule, i, {}, scan.rule->error()); + return; + } + const auto &rule = **scan.rule; + if (rule.output() != member.output || !valid_output(member.output)) + block(PlanIssue::stale_scan, i); + if (!scan.complete || !scan.header_uses || + (scan.method != ScanMethod::preprocess_md && scan.method != ScanMethod::preprocess_mmd && + scan.method != ScanMethod::missing_allowed)) + block(PlanIssue::incomplete_scan, i); + if (scan.method == ScanMethod::preprocess_mmd && !member.inputs.system_closure) + block(PlanIssue::incomplete_inputs, i); + + if (!bind_indices(scan.provided_headers, nodes_[i].provisions, rule.provides().size()) || + !scan.header_uses || + !bind_indices(*scan.header_uses, nodes_[i].imports, rule.requirements().size())) { + block(PlanIssue::unproven_mapping, i); + return; + } + // One invocation has one immutable filesystem view. Two identical source-path spellings + // in that invocation cannot bind to different header sources. Other invocations may have + // different views even when their printed paths match. + std::map header_paths; + auto bind_source = [&](const ModuleDescription &entry, std::string_view identity) { + if (!entry.source_path) + return; + const auto [it, inserted] = header_paths.emplace(*entry.source_path, identity); + if (!inserted && it->second != identity) + block(PlanIssue::unproven_mapping, i, *entry.source_path); + }; + for (const auto &header : scan.provided_headers) + bind_source(rule.provides()[header.index], header.source_identity); + for (const auto &use : *scan.header_uses) + bind_source(rule.requirements()[use.index], use.source_identity); + if (scan.writers.size() != rule.additional_outputs().size() + 1) { + block(PlanIssue::unproven_mapping, i, "output identities"); + } else { + for (const auto &writer : scan.writers) { + if (!identifier(writer)) { + block(PlanIssue::unproven_mapping, i, "output identity"); + continue; + } + const auto [it, inserted] = writers_.emplace(writer, i); + if (!inserted) { + local(i, PlanIssue::writer_collision, writer); + local(it->second, PlanIssue::writer_collision, writer); + } + } + } + index_claims(i, rule); +} + +void Planner::index_claims(Index i, const ScanRule &rule) { + const auto &node = nodes_[i]; + auto &kind = plan.units[i].kind; + const auto explicit_kind = node.scan->import_only_kind; + if (explicit_kind != UnitKind::unknown) { + if (rule.provides().empty() && + (explicit_kind == UnitKind::ordinary || explicit_kind == UnitKind::implementation)) + kind = explicit_kind; + else + block(PlanIssue::unproven_mapping, i, "unit kind"); + } + for (Index j = 0; j < rule.provides().size(); ++j) { + const auto &entry = rule.provides()[j]; + const auto *header = node.provisions[j]; + if (entry.compiled_module_path || + (!header && (entry.source_path || !named_module(entry.logical_name) || + (!entry.is_interface && !entry.logical_name.contains(':'))))) { + block(PlanIssue::unproven_mapping, i, entry.logical_name); + continue; + } + const Claim key{header != nullptr, header ? header->source_identity : entry.logical_name}; + const auto [it, inserted] = providers_.emplace(key, Provider{i}); + if (!inserted && (it->second.first != i || !header)) { + it->second.ambiguous = true; + local(i, PlanIssue::duplicate_provider, key.second); + local(it->second.first, PlanIssue::duplicate_provider, key.second); + } + if (rule.provides().size() == 1) { + if (header) + kind = UnitKind::header_unit; + else if (entry.logical_name.contains(':')) + kind = entry.is_interface ? UnitKind::interface_partition + : UnitKind::internal_partition; + else if (entry.is_interface) + kind = UnitKind::primary_interface; + } + } +} + +void Planner::link_imports(Index i) { + auto &node = nodes_[i]; + const auto &requirements = (**node.scan->rule).requirements(); + for (Index j = 0; j < requirements.size(); ++j) { + const auto &entry = requirements[j]; + const auto *use = node.imports[j]; + if (entry.compiled_module_path || + (!use && (entry.source_path || entry.lookup != LookupMethod::by_name || + !named_module(entry.logical_name)))) { + // An unbound header lookup may have hidden macro-dependent claims in this scan. + block(PlanIssue::unproven_mapping, i, entry.logical_name); + continue; + } + const Claim key{use != nullptr, use ? use->source_identity : entry.logical_name}; + const auto provider = providers_.find(key); + if (provider == providers_.end()) { + local(i, PlanIssue::missing_provider, key.second); + if (use) + block(PlanIssue::incomplete_scan, i, key.second); + continue; + } + if (provider->second.ambiguous) { + local(i, PlanIssue::duplicate_provider, key.second); + if (use) + block(PlanIssue::incomplete_scan, i, key.second); + continue; + } + const auto dependency = provider->second.first; + node.dependencies.push_back(dependency); + if (use) { + const auto &member = plan.units[dependency].member; + const auto &staged = member.staged_header; + if (!use->loaded_generation || !identifier(*use->loaded_generation) || !staged || + staged->generation != *use->loaded_generation || + staged->source_identity != use->source_identity || staged->domain != plan.domain || + staged->producer != member.context || staged->inputs != member.inputs) + block(PlanIssue::stale_header, i, key.second); + } + } + auto &dependencies = node.dependencies; + std::ranges::sort(dependencies); + dependencies.erase(std::unique(dependencies.begin(), dependencies.end()), dependencies.end()); + for (const auto dependency : dependencies) + plan.units[dependency].consumers.push_back(i); +} + +void Planner::order_from(Index requested) { + enum class Mark { unseen, visiting, finished }; + struct Frame { + Index unit, next{}; + }; + std::vector marks(nodes_.size(), Mark::unseen); + std::vector stack; + auto enter = [&](Index unit) { + marks[unit] = Mark::visiting; + stack.push_back({unit}); + const auto &issues = nodes_[unit].issues; + plan.blockers.insert(plan.blockers.end(), issues.begin(), issues.end()); + }; + enter(requested); + while (!stack.empty()) { + auto &frame = stack.back(); + const auto &dependencies = nodes_[frame.unit].dependencies; + if (frame.next == dependencies.size()) { + marks[frame.unit] = Mark::finished; + plan.order.push_back(plan.units[frame.unit].member.context); + stack.pop_back(); + continue; + } + const auto next = dependencies[frame.next++]; + if (marks[next] == Mark::unseen) + enter(next); + else if (marks[next] == Mark::visiting) + block(PlanIssue::cycle, next); + } + if (!plan.blockers.empty()) + plan.order.clear(); +} + +void Planner::collect(const ModuleCensus &census, std::span scans, + const Context &requested) { + if (census.members.size() > max_units || scans.size() > max_units) + throw GraphLimit{}; + Budget budget; + budget.domain(census.domain); + budget.field(census.revision.size()); + budget.context(requested); + for (const auto &member : census.members) + budget.member(member); + for (const auto &scan : scans) + budget.scan(scan); + + if (!census.closed || !identifier(census.revision) || !census.domain.generation || + !identifier(census.domain.compatibility) || !identifier(census.domain.lookup)) { + block(PlanIssue::incomplete_census); + return; + } + plan.domain = census.domain; + plan.census_revision = census.revision; + plan.units.reserve(census.members.size()); + for (const auto &member : census.members) + plan.units.push_back({member, UnitKind::unknown, {}}); + std::ranges::sort(plan.units, {}, + [](const auto &unit) -> const Context & { return unit.member.context; }); + std::map ids; + for (Index i = 0; i < plan.units.size(); ++i) { + const auto &member = plan.units[i].member; + if (!ids.emplace(member.context, i).second) + block(PlanIssue::duplicate_member, i); + if (!plan.domain.generation->find(member.context)) + block(PlanIssue::invalid_context, i); + } + const auto request = ids.find(requested); + if (request == ids.end()) + block(PlanIssue::invalid_context); + if (!plan.blockers.empty()) + return; + nodes_.resize(plan.units.size()); + for (const auto &scan : scans) { + const auto id = ids.find(scan.context); + if (id == ids.end()) + continue; + auto &node = nodes_[id->second]; + if (scan.domain != census.domain) + node.foreign = true; + else if (node.scan) + node.duplicate = true; + else + node.scan = &scan; + } + // A failed or incomplete member may be another provider even if no positive edge leads + // to it. Check all claims before resolving the requested component. + for (Index i = 0; i < nodes_.size(); ++i) + index_scan(i); + if (plan.blockers.empty()) { + for (Index i = 0; i < nodes_.size(); ++i) + link_imports(i); + plan.claims_complete = plan.blockers.empty(); + order_from(request->second); + } + if (!plan.claims_complete) { + for (auto &unit : plan.units) { + unit.kind = UnitKind::unknown; + unit.consumers.clear(); + } + } +} + +} // namespace + +ScanResult decode_scan(std::string_view bytes, const ExpectedOutput &expected) { + if (bytes.size() > max_scan_bytes || expected.spelling.size() > max_field_bytes || + expected.working_directory.native().size() > max_field_bytes) + return std::unexpected(ScanError::limit); + if (!valid_output(expected)) + return std::unexpected(ScanError::invalid_invocation); + auto parsed = P::parse_json(bytes, max_scan_depth); + if (!parsed) + return std::unexpected(parsed.error() == "JSON nesting exceeds depth limit" + ? ScanError::limit + : ScanError::invalid_json); + try { + std::size_t remaining = 16 * max_rule_items; + check_tree(*parsed, remaining); + const auto &envelope = object(*parsed); + zero_version(envelope, "version", true); + zero_version(envelope, "revision", false); + check_fields(envelope, {"version", "revision", "rules"}); + const auto rules = array_field(envelope, "rules"); + if (rules.size() != 1) + throw ScanError::invalid_shape; + const auto &fields = object(rules.front()); + check_fields(fields, + {"work-directory", "primary-output", "outputs", "provides", "requires"}); + if (const auto cwd = optional_text(fields, "work-directory"); + cwd && *cwd != expected.working_directory.string()) + throw ScanError::wrong_directory; + if (text_field(P::find_member(fields, "primary-output")) != expected.spelling) + throw ScanError::wrong_output; + const auto outputs = array_field(fields, "outputs"); + const auto provides = array_field(fields, "provides"); + const auto requirements = array_field(fields, "requires"); + if (outputs.size() + provides.size() + requirements.size() > max_rule_items) + throw ScanError::limit; + ScanRule rule; + rule.output_ = expected; + rule.wire_bytes_ = bytes.size(); + std::set seen{expected.spelling}; + for (const auto &output : outputs) { + const auto path = text_field(&output); + if (!seen.insert(path).second) + throw ScanError::invalid_shape; + rule.additional_outputs_.emplace_back(path); + } + rule.provides_ = descriptions(provides); + rule.requirements_ = descriptions(requirements); + return rule; + } catch (ScanError error) { + return std::unexpected(error); + } +} + +ModulePlan build_module_plan(const ModuleCensus &census, std::span scans, + const Context &requested) { + Planner planner; + try { + planner.collect(census, scans, requested); + } catch (const GraphLimit &) { + planner.plan = {}; + planner.plan.blockers.push_back({PlanIssue::limit, {}, {}, {}}); + } + auto &issues = planner.plan.blockers; + std::ranges::sort(issues); + issues.erase(std::unique(issues.begin(), issues.end()), issues.end()); + return std::move(planner.plan); +} + +bool ModulePlan::matches_census(const ModuleCensus ¤t) const { + if (!current.closed || units.empty() || units.size() > max_units || + units.size() != current.members.size() || domain != current.domain || + census_revision != current.revision) + return false; + Budget budget; + std::vector seen(units.size()); + for (const auto &member : current.members) { + try { + budget.member(member); + } catch (const GraphLimit &) { + return false; + } + const auto it = std::ranges::lower_bound( + units, member.context, {}, + [](const auto &unit) -> const Context & { return unit.member.context; }); + if (it == units.end() || it->member != member) + return false; + const auto index = static_cast(it - units.begin()); + if (seen[index]) + return false; + seen[index] = true; + } + return true; +} + +} // namespace vls::modules diff --git a/src/modules/ModuleWorkQueue.cpp b/src/modules/ModuleWorkQueue.cpp new file mode 100644 index 0000000..65beba9 --- /dev/null +++ b/src/modules/ModuleWorkQueue.cpp @@ -0,0 +1,86 @@ +#include + +#include + +namespace vls::modules { +namespace { +std::size_t slot(ModuleWorkKind kind) { return kind == ModuleWorkKind::scan ? 0 : 1; } +scheduler::Priority priority(ModuleWorkKind kind) { + return kind == ModuleWorkKind::scan ? scheduler::Priority::background + : scheduler::Priority::artifact; +} +} // namespace + +ModuleWorkQueue::ModuleWorkQueue(scheduler::Scheduler &scheduler) : scheduler_(scheduler) {} + +std::string ModuleWorkQueue::key(std::string_view document, ModuleWorkKind kind) { + return (kind == ModuleWorkKind::scan ? "scan:" : "artifact:") + std::string{document}; +} + +bool ModuleWorkQueue::submit(std::string document, ModuleWorkKind kind, std::uint64_t revision, + ModuleWork work, std::function completion) { + if (document.empty() || document.size() > 4096 || !work || revision == 0) + return false; + { + std::lock_guard lock{mutex_}; + auto &latest = revisions_[slot(kind)][document]; + if (revision <= latest) + return false; + latest = revision; + ++counts_.submitted; + } + const auto task_key = key(document, kind); + const bool accepted = scheduler_.submit( + {.priority = priority(kind), .key = task_key, .revision = revision, .memory_mib = 1}, + [work = std::move(work)](std::stop_token stop) { return work(stop); }, + [this, document, kind, revision, + completion = std::move(completion)](scheduler::Result result) { + { + std::lock_guard lock{mutex_}; + if (result.outcome == scheduler::Outcome::completed) + ++counts_.completed; + else if (result.outcome == scheduler::Outcome::cancelled || + result.outcome == scheduler::Outcome::timed_out) + ++counts_.cancelled; + else + ++counts_.failed; + } + if (completion) + completion(ModuleTaskResult{document, kind, revision, result.outcome, + std::move(result.detail)}); + }); + if (!accepted) { + std::lock_guard lock{mutex_}; + if (revisions_[slot(kind)][document] == revision) + revisions_[slot(kind)].erase(document); + return false; + } + return true; +} + +void ModuleWorkQueue::cancel(std::string_view document) { + if (document.empty()) + return; + scheduler_.cancel(key(document, ModuleWorkKind::scan)); + scheduler_.cancel(key(document, ModuleWorkKind::artifact)); +} + +void ModuleWorkQueue::cancel_all() { + std::map revisions[2]; + { + std::lock_guard lock{mutex_}; + revisions[0] = revisions_[0]; + revisions[1] = revisions_[1]; + } + for (const auto &[document, revision] : revisions[0]) + scheduler_.cancel(key(document, ModuleWorkKind::scan)); + for (const auto &[document, revision] : revisions[1]) + scheduler_.cancel(key(document, ModuleWorkKind::artifact)); +} + +ModuleWorkQueue::Counts ModuleWorkQueue::counts() const { + std::lock_guard lock{mutex_}; + return counts_; +} + +} // namespace vls::modules diff --git a/src/modules/ScanCommand.cpp b/src/modules/ScanCommand.cpp new file mode 100644 index 0000000..74a783f --- /dev/null +++ b/src/modules/ScanCommand.cpp @@ -0,0 +1,65 @@ +#include + +#include + +namespace vls::modules { +namespace { +bool takes_value(std::string_view option) { + return option == "-o" || option == "-MF" || option == "-MT" || option == "-MQ" || + option == "-x"; +} +bool removed(std::string_view option) { + return option == "-c" || option == "-E" || option == "-MD" || option == "-MMD" || + option == "-M" || option == "-MM" || option == "-MG" || option == "-fsyntax-only" || + option.starts_with("-fdiagnostics-") || option.starts_with("-fdeps-") || + option.starts_with("-fmodule-"); +} +} // namespace + +std::expected +build_scan_invocation(const Build::BuildContext &context, const ExpectedOutput &output, + const std::filesystem::path &dependency_file) { + if (!context.semantic_arguments || context.semantic_arguments->empty()) + return std::unexpected{ScanCommandError::invalid_context}; + if (!dependency_file.is_absolute()) + return std::unexpected{ScanCommandError::relative_dependency_file}; + const auto &source = context.key.owning_tu.native(); + const auto &original = *context.semantic_arguments; + std::vector arguments; + arguments.reserve(original.size() + 8); + arguments.push_back(original.front()); + std::size_t sources{}; + for (std::size_t index = 1; index < original.size(); ++index) { + const std::string_view argument = original[index]; + if (argument == source) { + ++sources; + continue; + } + if (removed(argument)) + continue; + if (takes_value(argument)) { + if (index + 1 == original.size()) + return std::unexpected{ScanCommandError::invalid_context}; + ++index; + continue; + } + if (argument.starts_with("-o") && argument.size() > 2) + continue; + if (argument.starts_with("-fdeps-") || argument.starts_with("-fmodule-")) + continue; + arguments.push_back(original[index]); + } + if (sources == 0) + return std::unexpected{ScanCommandError::missing_source}; + if (sources != 1) + return std::unexpected{ScanCommandError::duplicate_source}; + if (arguments.size() > 1000) + return std::unexpected{ScanCommandError::limit}; + arguments.insert(arguments.end(), + {"-E", "-MD", "-fdeps-format=p1689r5", + "-fdeps-file=" + dependency_file.native(), "-fdeps-target=" + output.spelling, + "-o", "/dev/null", source}); + return ScanInvocation{std::move(arguments)}; +} + +} // namespace vls::modules diff --git a/src/modules/ScheduledArtifacts.cpp b/src/modules/ScheduledArtifacts.cpp new file mode 100644 index 0000000..aeee2f8 --- /dev/null +++ b/src/modules/ScheduledArtifacts.cpp @@ -0,0 +1,119 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace vls::modules { +namespace fs = std::filesystem; +namespace { +using namespace std::chrono_literals; + +struct Completion { + std::mutex mutex; + std::condition_variable changed; + bool done{}; + scheduler::Outcome outcome{scheduler::Outcome::failed}; + std::string detail; +}; + +std::string hex(std::string_view bytes) { + constexpr char digits[] = "0123456789abcdef"; + std::string text; + for (const unsigned char byte : bytes) { + text += digits[byte >> 4]; + text += digits[byte & 0xf]; + } + return text; +} + +struct Cleanup { + fs::path path; + ~Cleanup() { + std::error_code error; + fs::remove_all(path, error); + } +}; +} // namespace + +std::expected, std::string> +produce_module_artifacts_scheduled(const ModulePlan &plan, ArtifactCache &cache, + const fs::path &staging, ArtifactWork work, + scheduler::Scheduler &scheduler, std::stop_token stop) { + try { + if (!plan.ready()) + return std::unexpected("module plan is not ready"); + if (!work) + return std::unexpected("no artifact work"); + std::error_code error; + fs::remove_all(staging, error); + fs::create_directories(staging); + Cleanup cleanup{staging}; + std::map artifacts; + std::uint64_t revision{}; + for (const auto &key : plan.order) { + if (stop.stop_requested()) + return std::unexpected("artifact production cancelled"); + const auto unit = std::ranges::find_if(plan.units, [&](const auto &candidate) { + return candidate.member.context.alternative == key.alternative; + }); + if (unit == plan.units.end()) + return std::unexpected("planned unit is missing from the census"); + const auto output = staging / hex(key.alternative); + auto completion = std::make_shared(); + const bool accepted = scheduler.submit( + {.priority = scheduler::Priority::artifact, + .key = key.alternative, + .revision = ++revision, + .memory_mib = 1}, + [&work, key, output](std::stop_token token) { + auto produced = work(token, key, output); + if (!produced) + throw std::runtime_error(produced.error()); + return produced->native(); + }, + [completion](scheduler::Result result) { + std::lock_guard lock{completion->mutex}; + completion->done = true; + completion->outcome = result.outcome; + completion->detail = std::move(result.detail); + completion->changed.notify_all(); + }); + if (!accepted) + return std::unexpected("module artifact admission was refused"); + std::unique_lock lock{completion->mutex}; + while (!completion->done && !stop.stop_requested()) + completion->changed.wait_for(lock, 50ms); + const bool done = completion->done; + const auto outcome = completion->outcome; + const auto detail = completion->detail; + lock.unlock(); + if (!done || stop.stop_requested()) { + scheduler.cancel(key.alternative); + return std::unexpected("artifact production cancelled"); + } + if (outcome == scheduler::Outcome::cancelled || + outcome == scheduler::Outcome::timed_out) + return std::unexpected("artifact production cancelled"); + if (outcome != scheduler::Outcome::completed) + return std::unexpected("module artifact failed: " + detail); + if (!fs::is_regular_file(output, error) || error) + return std::unexpected("artifact work produced no regular file"); + const auto &inputs = unit->member.inputs; + ArtifactKey artifact{plan.domain.compatibility, key.alternative, + inputs.command + "|" + inputs.source + "|" + + inputs.textual_closure + "|" + + inputs.system_closure.value_or(""), + "cmi"}; + artifacts.emplace(std::move(artifact), output); + } + return cache.publish(artifacts); + } catch (const std::exception &error) { + return std::unexpected(error.what()); + } +} + +} // namespace vls::modules diff --git a/src/navigation/Navigation.cpp b/src/navigation/Navigation.cpp new file mode 100644 index 0000000..c534768 --- /dev/null +++ b/src/navigation/Navigation.cpp @@ -0,0 +1,132 @@ +#include + +#include +#include +#include + +namespace vls::navigation { +namespace { +bool contains(const Range &range, Position position) { + return range.start <= position && position <= range.end; +} + +bool identifier(std::string_view name) { + if (name.empty() || name.size() > 256) + return false; + for (std::size_t index = 0; index != name.size(); ++index) { + const char c = name[index]; + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || + (index && c >= '0' && c <= '9'))) + return false; + } + return true; +} + +bool generated(std::string_view name) { + return name.contains('$') || name.starts_with("_GLOBAL__") || name.contains('<'); +} +} // namespace + +std::expected binding_at(const FactSet &set, std::string_view path, + Position position) { + std::set candidates; + for (const auto &fact : set.facts) + if (fact.source == path && contains(fact.use, position)) + candidates.insert(fact.binding); + if (candidates.empty()) + return std::unexpected{Refusal::unknown_binding}; + if (candidates.size() != 1) + return std::unexpected{Refusal::ambiguous_binding}; + return *candidates.begin(); +} + +References references(const FactSet &set, const Binding &binding, std::size_t limit) { + References result; + std::set unique; + for (const auto &fact : set.facts) + if (fact.binding == binding) + unique.insert(Location{fact.source, fact.use}); + for (const auto &location : unique) { + if (result.locations.size() == limit) { + result.truncated = true; + break; + } + result.locations.push_back(location); + } + for (const auto &context : set.contexts) + if (!context.complete) + result.incomplete_contexts.push_back(context.context); + std::ranges::sort(result.incomplete_contexts); + result.coverage_complete = result.incomplete_contexts.empty(); + return result; +} + +RenamePlan prepare_rename(const FactSet &set, std::string_view path, Position position, + std::string_view replacement, bool transactional_client) { + RenamePlan plan; + const auto binding = binding_at(set, path, position); + if (!binding) { + plan.refusal = binding.error(); + plan.detail = "no unique binding at the requested position"; + return plan; + } + if (!identifier(replacement)) { + plan.refusal = Refusal::invalid_name; + plan.detail = "the replacement is not a plain identifier"; + return plan; + } + if (generated(replacement)) { + plan.refusal = Refusal::generated_name; + plan.detail = "the replacement looks like a generated name"; + return plan; + } + if (replacement == binding->name) { + plan.refusal = Refusal::unchanged_name; + plan.detail = "the replacement equals the current spelling"; + return plan; + } + for (const auto &context : set.contexts) + if (!context.complete) { + plan.refusal = Refusal::incomplete_coverage; + plan.detail = "incomplete analysis coverage in " + context.context + + (context.reason.empty() ? "" : ": " + context.reason); + return plan; + } + std::set> seen; + std::set files; + for (const auto &fact : set.facts) { + if (fact.binding != *binding) + continue; + if (const auto current = set.current_sources.find(fact.source); + current != set.current_sources.end() && current->second != fact.content) { + plan.refusal = Refusal::stale_source; + plan.detail = "the source changed after analysis: " + fact.source; + return plan; + } + if (!fact.editable) { + plan.refusal = Refusal::non_editable_origin; + plan.detail = "the binding has a non-editable origin: " + fact.source; + return plan; + } + if (seen.emplace(fact.source, fact.use).second) { + files.insert(fact.source); + plan.edits.push_back({fact.source, fact.use, std::string{replacement}, fact.content}); + } + } + if (plan.edits.empty()) { + plan.refusal = Refusal::unknown_binding; + plan.detail = "the binding has no proven occurrence"; + return plan; + } + if (files.size() > 1 && !transactional_client) { + plan.refusal = Refusal::multi_file_without_transaction; + plan.detail = "multi-file rename requires a transactional client"; + return plan; + } + std::ranges::sort(plan.edits, [](const auto &left, const auto &right) { + return std::tie(left.path, left.range) < std::tie(right.path, right.range); + }); + return plan; +} + +} // namespace vls::navigation diff --git a/src/reflection/Provenance.cpp b/src/reflection/Provenance.cpp new file mode 100644 index 0000000..5f5fb8c --- /dev/null +++ b/src/reflection/Provenance.cpp @@ -0,0 +1,541 @@ +#include + +#include + +#include +#include +#include +#include + +namespace vls::reflection { +namespace P = Void::LanguageServer::Protocol; +using Json = P::Json; + +namespace { +std::string_view origin_name(OriginKind kind) { + switch (kind) { + case OriginKind::spelling: + return "spelling"; + case OriginKind::expansion: + return "expansion"; + case OriginKind::splice: + return "splice"; + case OriginKind::reflected_declaration: + return "reflectedDeclaration"; + case OriginKind::synthesized: + return "synthesized"; + } + return "synthesized"; +} + +std::optional origin_kind(std::string_view name) { + for (const auto kind : {OriginKind::spelling, OriginKind::expansion, OriginKind::splice, + OriginKind::reflected_declaration, OriginKind::synthesized}) + if (origin_name(kind) == name) + return kind; + return std::nullopt; +} + +std::string_view value_name(ValueKind kind) { + switch (kind) { + case ValueKind::integral: + return "integral"; + case ValueKind::text: + return "text"; + case ValueKind::boolean: + return "boolean"; + case ValueKind::entity: + return "entity"; + case ValueKind::opaque: + return "opaque"; + case ValueKind::unavailable: + return "unavailable"; + } + return "unavailable"; +} + +std::optional value_kind(std::string_view name) { + for (const auto kind : {ValueKind::integral, ValueKind::text, ValueKind::boolean, + ValueKind::entity, ValueKind::opaque, ValueKind::unavailable}) + if (value_name(kind) == name) + return kind; + return std::nullopt; +} + +std::optional source_link(const Provenance &provenance) { + for (const auto &origin : provenance.origins) + if (origin.range) + return origin.range; + return std::nullopt; +} + +Json range_json(const Range &range) { + return Json{Json::Object{{"path", Json{range.path}}, + {"line", Json{std::int64_t{range.line}}}, + {"character", Json{std::int64_t{range.character}}}, + {"endLine", Json{std::int64_t{range.endLine}}}, + {"endCharacter", Json{std::int64_t{range.endCharacter}}}}}; +} + +std::expected parse_range(const Json *value) { + const auto *fields = P::as_object(value); + if (!fields) + return std::unexpected("reflection range is not an object"); + const auto *path = P::as_string(P::find_member(*fields, "path")); + const auto line = P::as_uint32(P::find_member(*fields, "line")); + const auto character = P::as_uint32(P::find_member(*fields, "character")); + const auto end_line = P::as_uint32(P::find_member(*fields, "endLine")); + const auto end_character = P::as_uint32(P::find_member(*fields, "endCharacter")); + if (!path || !line || !character || !end_line || !end_character) + return std::unexpected("reflection range is incomplete"); + return Range{*path, *line, *character, *end_line, *end_character}; +} + +Json provenance_json(const Provenance &provenance) { + Json::Array origins; + for (const auto &origin : provenance.origins) { + Json::Object fields{{"kind", Json{std::string{origin_name(origin.kind)}}}, + {"note", Json{origin.note}}, + {"range", origin.range ? range_json(*origin.range) : Json{}}, + {"entity", origin.entity ? Json{*origin.entity} : Json{}}}; + origins.push_back(Json{std::move(fields)}); + } + return Json{Json::Object{{"origins", Json{std::move(origins)}}, + {"gap", Json{provenance.gap}}, + {"context", Json{provenance.context}}}}; +} + +Json value_json(const Value &value) { + return Json{Json::Object{{"kind", Json{std::string{value_name(value.kind)}}}, + {"integral", Json{value.integral}}, + {"boolean", Json{value.boolean}}, + {"text", Json{value.text}}, + {"type", Json{value.type}}, + {"entity", Json{value.entity}}}}; +} + +Json entity_json(const Entity &entity) { + Json::Array members; + for (const auto &member : entity.members) + members.push_back( + Json{Json::Object{{"name", Json{member.name}}, {"value", value_json(member.value)}}}); + return Json{Json::Object{{"id", Json{entity.id}}, + {"name", Json{entity.name}}, + {"type", Json{entity.type}}, + {"synthesized", Json{entity.synthesized}}, + {"provenance", provenance_json(entity.provenance)}, + {"members", Json{std::move(members)}}}}; +} +} // namespace + +bool Provenance::navigable() const { + return std::ranges::any_of(origins, + [](const Origin &origin) { return origin.range.has_value(); }); +} + +bool Provenance::editable() const { + if (gap || origins.empty()) + return false; + if (origins.front().kind != OriginKind::spelling || !origins.front().range) + return false; + return std::ranges::none_of( + origins, [](const Origin &origin) { return origin.kind == OriginKind::synthesized; }); +} + +Snapshot::Snapshot(Limits limits) : limits_(limits) {} + +bool Snapshot::add(Entity entity) { + if (entities_.size() >= limits_.entities || entity.id.empty()) + return false; + if (entity.id.size() > limits_.nameBytes || entity.name.size() > limits_.nameBytes || + entity.type.size() > limits_.typeBytes || + entity.provenance.context.size() > limits_.contextBytes || + entity.provenance.origins.size() > limits_.originsPerProvenance || + entity.members.size() > limits_.membersPerEntity) + return false; + for (const auto &origin : entity.provenance.origins) + if (origin.note.size() > limits_.textBytes || + (origin.range && origin.range->path.size() > limits_.nameBytes)) + return false; + for (const auto &member : entity.members) { + if (member.name.size() > limits_.nameBytes || + member.value.type.size() > limits_.typeBytes || + member.value.text.size() > limits_.textBytes || + member.value.entity.size() > limits_.nameBytes) + return false; + } + if (contains(entity.id)) + return false; + entities_.push_back(std::move(entity)); + return true; +} + +bool Snapshot::contains(const EntityId &id) const { + return std::ranges::any_of(entities_, [&id](const Entity &entity) { return entity.id == id; }); +} + +const Entity *Snapshot::find(const EntityId &id) const { + const auto found = + std::ranges::find_if(entities_, [&id](const Entity &entity) { return entity.id == id; }); + return found == entities_.end() ? nullptr : &*found; +} + +const std::vector &Snapshot::entities() const noexcept { return entities_; } +std::size_t Snapshot::size() const { return entities_.size(); } +const Limits &Snapshot::limits() const noexcept { return limits_; } + +std::expected Snapshot::expand(const EntityId &root, + std::optional depth) const { + const auto *entity = find(root); + if (!entity) + return std::unexpected("unknown reflection entity"); + const std::size_t max_depth = depth.value_or(limits_.expansionDepth); + Expansion result; + std::vector path{root}; + bool stopped{}; + const auto walk = [&](const auto &self, const Entity ¤t, const std::string &prefix, + std::size_t level) -> void { + for (const auto &member : current.members) { + if (stopped) + return; + const std::string member_path = + prefix.empty() ? member.name : prefix + "." + member.name; + if (result.entries.size() >= limits_.expansionValues) { + result.truncated.push_back(member_path); + stopped = true; + return; + } + Expansion::Entry entry; + entry.path = member_path; + entry.depth = level; + entry.kind = member.value.kind; + entry.type = member.value.type; + entry.entity = member.value.entity; + switch (member.value.kind) { + case ValueKind::integral: + entry.text = std::to_string(member.value.integral); + break; + case ValueKind::boolean: + entry.text = member.value.boolean ? "true" : "false"; + break; + default: + entry.text = member.value.text; + break; + } + result.entries.push_back(std::move(entry)); + if (member.value.kind != ValueKind::entity) + continue; + if (std::ranges::find(path, member.value.entity) != path.end()) { + result.cycles.push_back(member_path); + continue; + } + const auto *next = find(member.value.entity); + if (!next) { + result.entries.back().kind = ValueKind::unavailable; + result.entries.back().text = "entity is not in this snapshot"; + continue; + } + result.entries.back().link = source_link(next->provenance); + if (level >= max_depth) { + result.truncated.push_back(member_path); + continue; + } + path.push_back(member.value.entity); + self(self, *next, member_path, level + 1); + path.pop_back(); + } + }; + walk(walk, *entity, {}, 1); + return result; +} + +VirtualView render(const Entity &entity, const Expansion &expansion, const Limits &limits) { + VirtualView view; + const std::size_t max_lines = limits.expansionValues + 1; + std::string header = entity.name.empty() ? std::string{""} : entity.name; + header += " : "; + header += entity.type.empty() ? std::string{""} : entity.type; + if (entity.synthesized) + header += " [generated]"; + if (entity.provenance.gap) + header += " [origin unavailable]"; + if (header.size() > limits.textBytes) + header.resize(limits.textBytes); + view.lines.push_back( + VirtualLine{.text = std::move(header), .depth = 0, .link = source_link(entity.provenance)}); + for (const auto &entry : expansion.entries) { + if (view.lines.size() >= max_lines) { + view.truncated = true; + break; + } + const auto separator = entry.path.rfind('.'); + const auto name = + separator == std::string::npos ? entry.path : entry.path.substr(separator + 1); + std::string text(2 * std::min(entry.depth, 32), ' '); + text += name; + if (!entry.type.empty()) + text += " : " + entry.type; + if (entry.kind == ValueKind::entity) + text += " = "; + else if (!entry.text.empty()) + text += " = " + entry.text; + else if (entry.kind == ValueKind::opaque || entry.kind == ValueKind::unavailable) + text += " = "; + if (text.size() > limits.textBytes) + text.resize(limits.textBytes); + view.lines.push_back( + VirtualLine{.text = std::move(text), .depth = entry.depth, .link = entry.link}); + } + for (const auto &path : expansion.cycles) { + if (view.lines.size() >= max_lines) { + view.truncated = true; + break; + } + view.lines.push_back(VirtualLine{.text = "! cycle: " + path + " repeats on this path", + .depth = 0, + .link = std::nullopt}); + } + for (const auto &path : expansion.truncated) { + if (view.lines.size() >= max_lines) { + view.truncated = true; + break; + } + view.lines.push_back( + VirtualLine{.text = "! truncated: " + path, .depth = 0, .link = std::nullopt}); + } + return view; +} + +std::vector locations(const Provenance &provenance, std::size_t limit) { + std::vector result; + for (const auto &origin : provenance.origins) { + if (!origin.range || result.size() >= limit) + continue; + if (std::ranges::find(result, *origin.range) == result.end()) + result.push_back(*origin.range); + } + return result; +} + +Hover hover(const Entity &entity, const Expansion &expansion, const Limits &limits) { + const auto view = render(entity, expansion, limits); + Hover result; + result.markup = "```text\n"; + for (const auto &line : view.lines) { + result.markup += line.text; + result.markup += "\n"; + } + result.markup += "```\n"; + const auto links = locations(entity.provenance, 8); + if (!links.empty()) { + result.markup += "\nSources:\n"; + for (const auto &link : links) + result.markup += "- `" + link.path + ":" + std::to_string(link.line) + ":" + + std::to_string(link.character) + "`\n"; + } + if (!entity.provenance.origins.empty() && entity.provenance.origins.front().range) + result.range = entity.provenance.origins.front().range; + return result; +} + +Snapshot snapshot_from_splices(std::span splices, Limits limits) { + Snapshot snapshot{limits}; + const auto range_at = [](std::string_view path, std::uint32_t line, std::uint32_t column) { + return Range{std::string{path}, line, column, line, column}; + }; + for (const auto &splice : splices) { + if (splice.source.empty() || splice.line == 0 || splice.byteColumn == 0) + continue; + const bool located = + !splice.targetSource.empty() && splice.targetLine && splice.targetByteColumn; + std::string id = "gcc:"; + id += splice.targetKind.empty() ? "value" : splice.targetKind; + id += ":"; + id += splice.targetName.empty() ? "" : splice.targetName; + id += "@"; + if (located) + id += splice.targetSource + ":" + std::to_string(*splice.targetLine) + ":" + + std::to_string(*splice.targetByteColumn); + else + id += splice.source + ":" + std::to_string(splice.line) + ":" + + std::to_string(splice.byteColumn); + if (snapshot.contains(id)) + continue; + Entity entity; + entity.id = id; + entity.name = splice.targetName.empty() ? "" : splice.targetName; + entity.synthesized = !located; + entity.provenance.context = "gcc-splice"; + entity.provenance.origins.push_back( + Origin{.kind = OriginKind::splice, + .range = range_at(splice.source, splice.line, splice.byteColumn), + .entity = id, + .note = "splice site"}); + if (located) + entity.provenance.origins.push_back( + Origin{.kind = OriginKind::reflected_declaration, + .range = range_at(splice.targetSource, *splice.targetLine, + *splice.targetByteColumn), + .entity = id, + .note = splice.targetKind}); + else + entity.provenance.gap = true; + if (!snapshot.add(std::move(entity))) + break; + } + return snapshot; +} + +std::expected Snapshot::serialize() const { + std::vector ordered; + ordered.reserve(entities_.size()); + for (const auto &entity : entities_) + ordered.push_back(&entity); + std::ranges::sort(ordered, + [](const Entity *left, const Entity *right) { return left->id < right->id; }); + Json::Array entities; + for (const auto *entity : ordered) + entities.push_back(entity_json(*entity)); + const Json root{Json::Object{{"schema", Json{std::int64_t{schema_version}}}, + {"entities", Json{std::move(entities)}}}}; + auto encoded = P::serialize_json(root); + if (!encoded) + return std::unexpected(encoded.error()); + if (encoded->size() > limits_.snapshotBytes) + return std::unexpected("reflection snapshot exceeds its byte bound"); + return encoded; +} + +std::expected Snapshot::parse(std::string_view bytes, Limits limits) { + if (bytes.size() > limits.snapshotBytes) + return std::unexpected("reflection snapshot exceeds its byte bound"); + auto parsed = P::parse_json(bytes, 16); + if (!parsed) + return std::unexpected("reflection snapshot is not valid JSON"); + const auto *fields = P::as_object(&*parsed); + if (!fields) + return std::unexpected("reflection snapshot is not an object"); + const auto schema = P::as_int64(P::find_member(*fields, "schema")); + if (!schema || *schema != schema_version) + return std::unexpected("unsupported reflection schema version"); + const auto *entities = P::as_array(P::find_member(*fields, "entities")); + if (!entities) + return std::unexpected("reflection snapshot lacks an entity list"); + Snapshot snapshot{limits}; + std::set seen; + for (const auto &item : *entities) { + const auto *entity_fields = P::as_object(&item); + if (!entity_fields) + return std::unexpected("reflection entity is not an object"); + const auto *id = P::as_string(P::find_member(*entity_fields, "id")); + const auto *name = P::as_string(P::find_member(*entity_fields, "name")); + const auto *type = P::as_string(P::find_member(*entity_fields, "type")); + const auto synthesized = P::as_bool(P::find_member(*entity_fields, "synthesized")); + const auto *provenance = P::as_object(P::find_member(*entity_fields, "provenance")); + const auto *members = P::as_array(P::find_member(*entity_fields, "members")); + if (!id || !name || !type || !synthesized || !provenance || !members) + return std::unexpected("reflection entity is incomplete"); + if (!seen.insert(*id).second) + return std::unexpected("duplicate reflection entity identity"); + Entity entity; + entity.id = *id; + entity.name = *name; + entity.type = *type; + entity.synthesized = *synthesized; + const auto *context = P::as_string(P::find_member(*provenance, "context")); + const auto gap = P::as_bool(P::find_member(*provenance, "gap")); + const auto *origins = P::as_array(P::find_member(*provenance, "origins")); + if (!context || !gap || !origins) + return std::unexpected("reflection provenance is incomplete"); + entity.provenance.context = *context; + entity.provenance.gap = *gap; + for (const auto &origin_item : *origins) { + const auto *origin_fields = P::as_object(&origin_item); + if (!origin_fields) + return std::unexpected("reflection origin is not an object"); + const auto *kind_name = P::as_string(P::find_member(*origin_fields, "kind")); + const auto *note = P::as_string(P::find_member(*origin_fields, "note")); + const auto kind = kind_name ? origin_kind(*kind_name) : std::nullopt; + if (!kind || !note) + return std::unexpected("reflection origin is invalid"); + Origin origin; + origin.kind = *kind; + origin.note = *note; + const auto *range = P::find_member(*origin_fields, "range"); + if (range && !std::holds_alternative(range->value)) { + auto parsed_range = parse_range(range); + if (!parsed_range) + return std::unexpected(parsed_range.error()); + origin.range = std::move(*parsed_range); + } + const auto *target = P::find_member(*origin_fields, "entity"); + if (target && !std::holds_alternative(target->value)) { + const auto *value = P::as_string(target); + if (!value) + return std::unexpected("reflection origin entity is invalid"); + origin.entity = *value; + } + entity.provenance.origins.push_back(std::move(origin)); + } + for (const auto &member_item : *members) { + const auto *member_fields = P::as_object(&member_item); + if (!member_fields) + return std::unexpected("reflection member is not an object"); + const auto *member_name = P::as_string(P::find_member(*member_fields, "name")); + const auto *value_fields = P::as_object(P::find_member(*member_fields, "value")); + if (!member_name || !value_fields) + return std::unexpected("reflection member is incomplete"); + const auto *kind_name = P::as_string(P::find_member(*value_fields, "kind")); + const auto kind = kind_name ? value_kind(*kind_name) : std::nullopt; + const auto integral = P::as_int64(P::find_member(*value_fields, "integral")); + const auto boolean = P::as_bool(P::find_member(*value_fields, "boolean")); + const auto *text = P::as_string(P::find_member(*value_fields, "text")); + const auto *value_type = P::as_string(P::find_member(*value_fields, "type")); + const auto *target = P::as_string(P::find_member(*value_fields, "entity")); + if (!kind || !integral || !boolean || !text || !value_type || !target) + return std::unexpected("reflection member value is invalid"); + entity.members.push_back(Member{*member_name, Value{.kind = *kind, + .integral = *integral, + .boolean = *boolean, + .text = *text, + .type = *value_type, + .entity = *target}}); + } + if (!snapshot.add(std::move(entity))) + return std::unexpected("reflection entity exceeds the snapshot limits"); + } + return snapshot; +} + +Capabilities::Capabilities(Limits limits) : limits_(limits) {} + +bool Capabilities::add(Capability capability) { + if (entries_.size() >= limits_.capabilities) + return false; + if (capability.proposal.empty() || capability.facility.empty() || + capability.proposal.size() > limits_.nameBytes || + capability.facility.size() > limits_.nameBytes || + capability.reason.size() > limits_.textBytes) + return false; + if (!capability.supported && capability.reason.empty()) + return false; + if (query(capability.proposal, capability.facility)) + return false; + entries_.push_back(std::move(capability)); + return true; +} + +std::expected Capabilities::query(std::string_view proposal, + std::string_view facility) const { + const auto found = std::ranges::find_if(entries_, [&](const Capability &entry) { + return entry.proposal == proposal && entry.facility == facility; + }); + if (found == entries_.end()) + return std::unexpected("unknown reflection capability: " + std::string{proposal} + "/" + + std::string{facility}); + return *found; +} + +std::size_t Capabilities::size() const { return entries_.size(); } + +} // namespace vls::reflection diff --git a/src/scheduler/Scheduler.cpp b/src/scheduler/Scheduler.cpp new file mode 100644 index 0000000..a70a3e6 --- /dev/null +++ b/src/scheduler/Scheduler.cpp @@ -0,0 +1,315 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::scheduler { +namespace { +using Clock = std::chrono::steady_clock; + +std::uint64_t nanoseconds(Clock::time_point from, Clock::time_point to) { + return static_cast( + std::chrono::duration_cast(to - from).count()); +} +std::size_t pool_index(Priority priority) { return static_cast(priority); } +} // namespace + +bool Budget::valid() const noexcept { + return foreground >= 1 && background >= 1 && artifact >= 1 && queued >= 1 && memory_mib >= 1 && + watchdog.count() > 0; +} + +struct Scheduler::State { + struct Task { + Estimate estimate; + Work work; + Completion completion; + std::stop_source stop; + Clock::time_point queued_at{Clock::now()}; + Clock::time_point started_at{}; + std::size_t pool{}; + bool started{}; + bool watchdog{}; + bool terminal{}; + }; + struct Pool { + std::deque> queue; + std::size_t running{}; + std::size_t limit{}; + }; + struct Terminal { + Completion completion; + Result result; + }; + + Budget budget; + mutable std::mutex mutex; + std::condition_variable changed, idle; + std::array pools; + std::unordered_map> active; + Metrics counters; + std::size_t running_memory{}; + // Terminal results whose completion callback has not returned yet. + std::size_t finishing{}; + bool stopping{}; + // Declared last so workers are joined before the state they read is destroyed. + std::vector workers; + std::jthread monitor; + + explicit State(Budget value) : budget(value) { + if (!budget.valid()) + throw std::invalid_argument("invalid scheduler budget"); + for (std::size_t index = 0; index != pools.size(); ++index) + pools[index].limit = index == pool_index(Priority::foreground) ? budget.foreground + : index == pool_index(Priority::background) ? budget.background + : budget.artifact; + for (std::size_t pool = 0; pool != pools.size(); ++pool) + for (std::size_t worker = 0; worker != pools[pool].limit; ++worker) + workers.emplace_back([this, pool] { work(pool); }); + monitor = std::jthread([this](std::stop_token token) { watch(token); }); + } + ~State() { + std::vector terminals; + { + std::lock_guard lock{mutex}; + stopping = true; + for (auto &pool : pools) { + for (auto &task : pool.queue) + if (auto terminal = + finish(*this, task, Outcome::cancelled, "scheduler shutdown")) + terminals.push_back(std::move(*terminal)); + pool.queue.clear(); + } + for (auto &[key, task] : active) + if (task->started) + task->stop.request_stop(); + changed.notify_all(); + } + for (auto &terminal : terminals) + terminal.completion(terminal.result); + } + + std::size_t total_running() const { + std::size_t count{}; + for (auto &pool : pools) + count += pool.running; + return count; + } + + static std::optional finish(State &state, const std::shared_ptr &task, + Outcome outcome, std::string detail) { + if (task->terminal) + return std::nullopt; + task->terminal = true; + const auto now = Clock::now(); + state.counters.queue_nanoseconds += + nanoseconds(task->queued_at, task->started ? task->started_at : now); + if (task->started) { + state.counters.run_nanoseconds += nanoseconds(task->started_at, now); + --state.pools[task->pool].running; + state.running_memory -= task->estimate.memory_mib; + } + switch (outcome) { + case Outcome::completed: + ++state.counters.completed; + break; + case Outcome::failed: + ++state.counters.failed; + break; + case Outcome::cancelled: + ++state.counters.cancelled; + break; + case Outcome::timed_out: + ++state.counters.timed_out; + break; + } + const auto entry = state.active.find(task->estimate.key); + if (entry != state.active.end() && entry->second == task) + state.active.erase(entry); + state.changed.notify_all(); + state.idle.notify_all(); + ++state.finishing; + return Terminal{task->completion, Result{task->estimate.key, task->estimate.revision, + outcome, std::move(detail)}}; + } + + // Invokes a terminal completion outside the lock, then makes drain observe it. + void deliver(Terminal terminal) { + terminal.completion(terminal.result); + std::lock_guard lock{mutex}; + --finishing; + idle.notify_all(); + } + + void work(std::size_t pool) { + std::unique_lock lock{mutex}; + for (;;) { + changed.wait(lock, [&] { + if (stopping) + return true; + const auto &queue = pools[pool].queue; + return std::ranges::any_of(queue, [&](const auto &task) { + return running_memory + task->estimate.memory_mib <= budget.memory_mib; + }); + }); + if (stopping) + return; + auto &queue = pools[pool].queue; + const auto selected = std::ranges::find_if(queue, [&](const auto &task) { + return running_memory + task->estimate.memory_mib <= budget.memory_mib; + }); + auto task = *selected; + queue.erase(selected); + ++pools[pool].running; + running_memory += task->estimate.memory_mib; + counters.running_peak = std::max(counters.running_peak, total_running()); + counters.running_memory_peak = std::max(counters.running_memory_peak, running_memory); + task->started = true; + task->started_at = Clock::now(); + lock.unlock(); + std::string detail; + Outcome outcome = Outcome::completed; + try { + detail = task->work(task->stop.get_token()); + } catch (const std::exception &error) { + detail = error.what(); + outcome = Outcome::failed; + } catch (...) { + detail = "unknown failure"; + outcome = Outcome::failed; + } + lock.lock(); + // A stopped task never reports success or failure: its result must not + // satisfy a publication promise. + if (task->stop.stop_requested()) + outcome = task->watchdog ? Outcome::timed_out : Outcome::cancelled; + auto terminal = finish(*this, task, outcome, std::move(detail)); + lock.unlock(); + if (terminal) + deliver(std::move(*terminal)); + lock.lock(); + } + } + + void watch(std::stop_token shutdown) { + std::unique_lock lock{mutex}; + while (!shutdown.stop_requested() && !stopping) { + changed.wait_for(lock, std::chrono::milliseconds(5)); + if (stopping) + return; + const auto now = Clock::now(); + for (auto &[key, task] : active) + if (task->started && !task->stop.stop_requested() && + now - task->started_at >= budget.watchdog) { + task->watchdog = true; + task->stop.request_stop(); + } + } + } + + bool submit(Estimate estimate, Work work, Completion completion) { + std::optional superseded; + { + std::lock_guard lock{mutex}; + if (stopping || !work || !completion || estimate.key.empty() || + estimate.key.size() > 512 || estimate.memory_mib > budget.memory_mib) + return false; + std::size_t queued{}; + for (auto &pool : pools) + queued += pool.queue.size(); + if (queued >= budget.queued) { + ++counters.rejected; + return false; + } + if (const auto entry = active.find(estimate.key); entry != active.end()) { + auto old = entry->second; + if (!old->started) { + auto &queue = pools[old->pool].queue; + const auto position = std::ranges::find(queue, old); + if (position != queue.end()) + queue.erase(position); + superseded = finish(*this, old, Outcome::cancelled, "superseded"); + } else + old->stop.request_stop(); + } + auto task = std::make_shared(); + task->estimate = std::move(estimate); + task->work = std::move(work); + task->completion = std::move(completion); + task->pool = pool_index(task->estimate.priority); + active[task->estimate.key] = task; + pools[task->pool].queue.push_back(task); + ++counters.accepted; + counters.queued_peak = std::max(counters.queued_peak, queued + 1); + changed.notify_all(); + } + if (superseded) + deliver(std::move(*superseded)); + return true; + } + + void cancel(std::string_view key) { + std::optional terminal; + { + std::lock_guard lock{mutex}; + const auto entry = active.find(std::string{key}); + if (entry == active.end()) + return; + auto task = entry->second; + if (!task->started) { + auto &queue = pools[task->pool].queue; + const auto position = std::ranges::find(queue, task); + if (position != queue.end()) + queue.erase(position); + terminal = finish(*this, task, Outcome::cancelled, "cancelled"); + } else + task->stop.request_stop(); + } + if (terminal) + deliver(std::move(*terminal)); + } + + void cancel_all() { + std::vector keys; + { + std::lock_guard lock{mutex}; + keys.reserve(active.size()); + for (auto &[key, task] : active) + keys.push_back(key); + } + for (auto &key : keys) + cancel(key); + } + + void drain() { + std::unique_lock lock{mutex}; + idle.wait(lock, [&] { return active.empty() && finishing == 0; }); + } + + Metrics metrics() const { + std::lock_guard lock{mutex}; + return counters; + } +}; + +Scheduler::Scheduler(Budget budget) : state_(std::make_unique(budget)) {} +Scheduler::~Scheduler() = default; + +bool Scheduler::submit(Estimate estimate, Work work, Completion completion) { + return state_->submit(std::move(estimate), std::move(work), std::move(completion)); +} +void Scheduler::cancel(std::string_view key) { state_->cancel(key); } +void Scheduler::cancel_all() { state_->cancel_all(); } +void Scheduler::drain() { state_->drain(); } +Metrics Scheduler::metrics() const { return state_->metrics(); } +const Budget &Scheduler::budget() const noexcept { return state_->budget; } + +} // namespace vls::scheduler diff --git a/src/semantic/Diagnostics.cpp b/src/semantic/Diagnostics.cpp new file mode 100644 index 0000000..61999b4 --- /dev/null +++ b/src/semantic/Diagnostics.cpp @@ -0,0 +1,399 @@ +#include + +#include + +#include +#include +#include + +namespace vls::semantic { +namespace { +namespace P = Void::LanguageServer::Protocol; +using Json = P::Json; +using Object = Json::Object; +using Error = DiagnosticError; +template using Result = std::expected; + +constexpr std::size_t max_report_bytes = 4 * 1024 * 1024; +constexpr std::size_t max_artifacts = 2048, max_results = 4096, max_locations = 16384; +constexpr std::size_t max_name = 16384, max_message = 65536; +constexpr std::string_view bom = "\xef\xbb\xbf"; + +// Cap container allocation in Void's JSON value tree before parsing. Brackets +// and commas in embedded source/diagnostic strings are ordinary content. +bool within_structure_limit(std::string_view bytes) { + std::size_t remaining = 128 * 1024; + bool quoted = false, escaped = false; + for (const char c : bytes) { + if (quoted) { + if (escaped) + escaped = false; + else if (c == '\\') + escaped = true; + else if (c == '"') + quoted = false; + } else if (c == '"') { + quoted = true; + } else if (c == '[' || c == '{' || c == ',' || c == ':') { + if (remaining == 0) + return false; + --remaining; + } + } + return true; +} + +const Json *member(const Object *obj, std::string_view key) { + return obj ? P::find_member(*obj, key) : nullptr; +} +const std::string *string(const Object *obj, std::string_view key) { + return P::as_string(member(obj, key)); +} +const Object *object(const Object *obj, std::string_view key) { + return P::as_object(member(obj, key)); +} +const Object *only_object(const Object *obj, std::string_view key) { + const auto *list = P::as_array(member(obj, key)); + return list && list->size() == 1 ? P::as_object(&list->front()) : nullptr; +} +bool equals(const Object *obj, std::string_view key, std::string_view value) { + const auto *text = string(obj, key); + return text && *text == value; +} +std::optional natural(const Json *value) { + if (!value) + return {}; + const auto *integer = std::get_if(&value->value); + if (!integer || *integer < 0 || *integer > std::numeric_limits::max()) + return {}; + return static_cast(*integer); +} + +std::optional artifact_name(const Object *record, const Object *bases) { + const auto *uri = string(record, "uri"); + if (!uri || uri->empty() || uri->size() > max_name) + return {}; + const auto *base_id = member(record, "uriBaseId"); + if (!base_id) + return ArtifactName{*uri, {}}; + const auto *id = P::as_string(base_id); + const auto *base = id ? object(bases, *id) : nullptr; + const auto *base_uri = string(base, "uri"); + if (!base_uri || base_uri->empty() || base_uri->size() > max_name || member(base, "uriBaseId")) + return {}; + return ArtifactName{*uri, *base_uri}; +} + +struct BoundArtifact { + const DiagnosticArtifact *file{}; + bool contents_match{}; +}; + +struct Reader { + explicit Reader(const DiagnosticJob &source_job) : job(source_job) {} + const DiagnosticJob &job; + const Object *bases{}; + std::map bindings; + std::map listed; + std::vector by_index; + std::size_t positions_left{max_locations}, column_work{32 * 1024 * 1024}; + + Result bind(const Object *run) { + if (job.artifacts.size() > max_artifacts) + return std::unexpected(Error::resource_limit); + std::size_t names_left = 2 * 1024 * 1024; + for (const auto &file : job.artifacts) { + if (!file.snapshot || file.name.uri.empty() || file.name.uri.size() > max_name || + file.name.base_uri.size() > max_name) + return std::unexpected(Error::invalid_job); + const auto cost = file.name.uri.size() + file.name.base_uri.size(); + if (cost > names_left) + return std::unexpected(Error::resource_limit); + names_left -= cost; + if (!bindings.emplace(file.name, &file).second) + return std::unexpected(Error::invalid_job); + } + bases = object(run, "originalUriBaseIds"); + if (member(run, "originalUriBaseIds") && !bases) + return std::unexpected(Error::malformed_report); + const auto *files = P::as_array(member(run, "artifacts")); + if (!files) { + if (member(run, "artifacts")) + return std::unexpected(Error::malformed_report); + return false; + } + if (files->size() > max_artifacts) + return std::unexpected(Error::resource_limit); + bool found_owner = false; + for (const auto &item : *files) { + const auto *record = P::as_object(&item); + const auto *location = object(record, "location"); + if (const auto *self_index = member(location, "index")) { + const auto index = natural(self_index); + if (!index || *index != by_index.size()) + return std::unexpected(Error::malformed_report); + } + const auto name = artifact_name(location, bases); + if (!name || !listed.emplace(*name, by_index.size()).second) + return std::unexpected(Error::malformed_report); + auto binding = bindings.find(*name); + auto *file = binding == bindings.end() ? nullptr : binding->second; + bool matches = true; + if (member(record, "contents")) { + const auto *bytes = string(object(record, "contents"), "text"); + if (file) { + const std::string_view input = file->snapshot->text; + matches = bytes && (*bytes == input || + (input.starts_with(bom) && *bytes == input.substr(3))); + } + } + by_index.push_back({file, matches}); + if (!member(record, "roles")) + continue; + const auto *roles = P::as_array(member(record, "roles")); + if (!roles) + return std::unexpected(Error::malformed_report); + for (const auto &role : *roles) { + const auto *text = P::as_string(&role); + if (!text) + return std::unexpected(Error::malformed_report); + if (*text == "analysisTarget") { + if (found_owner || !file || file->snapshot != job.owner || !matches) + return std::unexpected(Error::wrong_owner); + found_owner = true; + } + } + } + return found_owner; + } + + std::optional binding(const Object *location) const { + const auto *index = member(location, "index"); + std::optional reference; + if (index) { + reference = natural(index); + if (!reference || *reference >= by_index.size()) + return {}; + } + if (member(location, "uri")) { + auto name = artifact_name(location, bases); + if (!name) + return {}; + const auto found = listed.find(*name); + if (found == listed.end() || (reference && *reference != found->second)) + return {}; + return by_index[found->second]; + } + if (member(location, "uriBaseId") || !reference) + return {}; + return by_index[*reference]; + } + + Result> position(const Documents::DocumentSnapshot &snapshot, + std::uint32_t line, std::uint32_t column, + CoordinatePolicy policy) { + const auto start = snapshot.line_index.line_start_offset(line - 1); + const auto end = snapshot.line_index.line_content_end_offset(snapshot.text, line - 1); + if (!start || !end || *end < *start || *end > snapshot.text.size()) + return {}; + auto text = std::string_view{snapshot.text}.substr(*start, *end - *start); + std::size_t offset = 0; + if (line == 1 && text.starts_with(bom)) { + if (policy.bom == FirstLineBom::unknown) + return {}; + if (policy.bom == FirstLineBom::skipped) + offset = bom.size(); + } + const std::size_t target = column - 1; + // Also charge the subsequent UTF-16 conversion, which can scan the line prefix. + const auto charge = 2 * (std::min(target, text.size()) + offset + 1); + if (charge > column_work) + return std::unexpected(Error::resource_limit); + column_work -= charge; + if (policy.unit == ColumnUnit::utf8_bytes) { + if (target > text.size() - offset) + return {}; + offset += target; + } else { + std::size_t display = 0; + while (display < target && offset < text.size()) { + const auto ch = static_cast(text[offset++]); + if (ch == '\t' && policy.unit == ColumnUnit::gcc_display && policy.tabstop > 0 && + policy.tabstop <= 100) { + display += policy.tabstop - display % policy.tabstop; + } else if (ch >= 0x20 && ch <= 0x7e) { + ++display; + } else { + return {}; + } + } + if (display != target) + return {}; + // The prefix advanced strictly, but a following non-ASCII scalar + // can share this display column. Require a provable boundary. + if (offset < text.size() && static_cast(text[offset]) >= 0x80) + return {}; + } + auto pos = snapshot.offset_to_position(*start + offset); + if (!pos) + return {}; + return *pos; + } + + Result locate(const Object *loc, std::size_t result_index, + std::size_t location_index, bool related) { + if (positions_left == 0) + return std::unexpected(Error::resource_limit); + --positions_left; + const auto *physical = object(loc, "physicalLocation"); + if (!physical) + return DiagnosticLocation{}; + const auto file = binding(object(physical, "artifactLocation")); + if (!file || !file->file) + return DiagnosticLocation{LocationGap::unknown_artifact}; + if (!file->contents_match) + return DiagnosticLocation{LocationGap::artifact_mismatch}; + const auto *region = object(physical, "region"); + auto first = natural(member(region, "startLine")), + left = natural(member(region, "startColumn")); + auto last = member(region, "endLine") ? natural(member(region, "endLine")) : first; + auto right = natural(member(region, "endColumn")); + if (!first || !left || !last || !right || !*first || !*left || !*last || !*right || + *last < *first || (*last == *first && *right < *left)) + return DiagnosticLocation{LocationGap::incomplete_region}; + LocationRequest request{ + *file->file, {*first, *left, *last, *right}, result_index, location_index, related}; + const auto policy = job.physical_origin ? job.physical_origin(request) : std::nullopt; + if (!policy) + return DiagnosticLocation{LocationGap::unproven_origin}; + const auto &snapshot = file->file->snapshot; + auto start = position(*snapshot, *first, *left, *policy); + if (!start) + return std::unexpected(start.error()); + auto end = position(*snapshot, *last, *right, *policy); + if (!end) + return std::unexpected(end.error()); + if (!*start || !*end || **end < **start) + return DiagnosticLocation{LocationGap::ambiguous_column}; + return DiagnosticLocation{LocationGap::none, snapshot, Documents::Range{**start, **end}}; + } +}; + +std::optional severity(const Object *record) { + if (equals(record, "level", "error")) + return DiagnosticSeverity::error; + if (equals(record, "level", "warning")) + return DiagnosticSeverity::warning; + if (equals(record, "level", "note")) + return DiagnosticSeverity::information; + if (equals(record, "level", "none")) + return DiagnosticSeverity::hint; + return {}; +} + +Result append_locations(Reader &reader, const Json *value, std::size_t index, bool related, + CompilerDiagnostic &diagnostic) { + if (!value) + return {}; + const auto *locations = P::as_array(value); + if (!locations) + return std::unexpected(Error::malformed_report); + for (std::size_t i = 0; i != locations->size(); ++i) { + const auto *record = P::as_object(&(*locations)[i]); + if (!record) + return std::unexpected(Error::malformed_report); + auto location = reader.locate(record, index, i, related); + if (!location) + return std::unexpected(location.error()); + if (!related && i == 0) { + diagnostic.location = std::move(*location); + } else { + const auto *message = string(object(record, "message"), "text"); + if (message && message->size() > max_message) + return std::unexpected(Error::resource_limit); + diagnostic.related.push_back( + {message ? *message : std::string{}, std::move(*location)}); + } + } + return {}; +} +} // namespace + +std::expected +decode_gcc_diagnostics(const DiagnosticJob &job, const DiagnosticOutput &output) { + if (!job.owner || job.invocation_id.empty() || job.input_view_id.empty() || + job.invocation_id.size() > max_name || job.input_view_id.size() > max_name) + return std::unexpected(Error::invalid_job); + if (job.invocation_id != output.invocation_id || job.input_view_id != output.input_view_id) + return std::unexpected(Error::wrong_capture); + if (!output.stream_complete || output.sarif.empty()) + return std::unexpected(Error::incomplete_stream); + if (!output.exit_code || (*output.exit_code != 0 && *output.exit_code != 1)) + return std::unexpected(Error::failed_process); + if (output.sarif.size() > max_report_bytes || !within_structure_limit(output.sarif)) + return std::unexpected(Error::resource_limit); + auto report = P::parse_json(output.sarif, 40); + if (!report) + return std::unexpected(Error::malformed_report); + const auto *root = P::as_object(&*report); + const auto *run = only_object(root, "runs"); + const auto *driver = object(object(run, "tool"), "driver"); + if (!equals(root, "version", "2.1.0") || !equals(driver, "name", "GNU C++26") || + !equals(driver, "version", "16.2.0") || member(run, "columnKind")) + return std::unexpected(Error::unsupported_report); + const auto *invocation = only_object(run, "invocations"); + const auto success = P::as_bool(member(invocation, "executionSuccessful")); + const auto *notifications = P::as_array(member(invocation, "toolExecutionNotifications")); + if (!success || *success != (*output.exit_code == 0) || !notifications) + return std::unexpected(Error::malformed_report); + if (!notifications->empty()) + return std::unexpected(Error::tool_failure); + Reader reader{job}; + const auto owner_matched = reader.bind(run); + if (!owner_matched) + return std::unexpected(owner_matched.error()); + if (*success && !*owner_matched) + return std::unexpected(Error::wrong_owner); + // GCC can fail before opening its main file. Keep the invocation's message + // but do not bind positions to an unconfirmed translation unit. + if (!*owner_matched) { + reader.by_index.clear(); + reader.listed.clear(); + } + const auto *results = P::as_array(member(run, "results")); + if (!results) + return std::unexpected(Error::malformed_report); + if (results->size() > max_results) + return std::unexpected(Error::resource_limit); + DiagnosticBatch batch{ + job.invocation_id, job.input_view_id, job.owner, {}, job.inputs_complete && *owner_matched}; + bool source_error = false; + for (std::size_t i = 0; i != results->size(); ++i) { + const auto *record = P::as_object(&(*results)[i]); + const auto level = severity(record); + const auto *message = string(object(record, "message"), "text"); + const auto *rule = string(record, "ruleId"); + if (!level || !message || !rule || message->empty()) + return std::unexpected(Error::malformed_report); + if (message->size() > max_message || rule->size() > max_name) + return std::unexpected(Error::resource_limit); + CompilerDiagnostic diagnostic{*level, *message, *rule, {}, {}}; + if (auto primary = + append_locations(reader, member(record, "locations"), i, false, diagnostic); + !primary) + return std::unexpected(primary.error()); + if (auto related = + append_locations(reader, member(record, "relatedLocations"), i, true, diagnostic); + !related) + return std::unexpected(related.error()); + source_error |= *level == DiagnosticSeverity::error; + if (!diagnostic.location.range || *rule == "fatal error" || + *rule == "internal compiler error") + batch.complete_for_owner = false; + batch.diagnostics.push_back(std::move(diagnostic)); + } + if (source_error == *success) + return std::unexpected(Error::malformed_report); + return batch; +} +} // namespace vls::semantic diff --git a/src/semantic/EditorDiagnostics.cpp b/src/semantic/EditorDiagnostics.cpp new file mode 100644 index 0000000..d2b67c9 --- /dev/null +++ b/src/semantic/EditorDiagnostics.cpp @@ -0,0 +1,1193 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::semantic { +namespace P = Void::LanguageServer::Protocol; +namespace B = Void::LanguageServer::Build; +namespace W = Void::LanguageServer::Workspace; +namespace fs = std::filesystem; +using namespace std::chrono_literals; +namespace { +using Json = P::Json; +using Clock = std::chrono::steady_clock; +constexpr std::size_t max_documents = 12; + +Json position(const Documents::Position &p) { + return Json{Json::Object{{"line", Json{std::int64_t{p.line}}}, + {"character", Json{std::int64_t{p.character}}}}}; +} + +Json range_json(const Documents::Range &range) { + return Json{Json::Object{{"start", position(range.start)}, {"end", position(range.end)}}}; +} + +index::Location location_of(const Documents::Range &range, + const Documents::DocumentSnapshot &snapshot) { + return {snapshot.identity.canonical_path.native(), range.start.line, range.start.character, + range.end.line, range.end.character}; +} + +bool under(const fs::path &root, const fs::path &path) { + return std::mismatch(root.begin(), root.end(), path.begin(), path.end()).first == root.end(); +} + +std::string refusal_text(navigation::Refusal refusal) { + switch (refusal) { + case navigation::Refusal::unknown_binding: + return "no symbol at the requested position"; + case navigation::Refusal::ambiguous_binding: + return "the position resolves to more than one binding"; + case navigation::Refusal::incomplete_coverage: + return "analysis coverage is incomplete"; + case navigation::Refusal::stale_source: + return "the source changed after analysis"; + case navigation::Refusal::non_editable_origin: + return "the binding has a non-editable origin"; + case navigation::Refusal::generated_name: + return "the name is compiler-generated"; + case navigation::Refusal::invalid_name: + return "the replacement is not a plain identifier"; + case navigation::Refusal::unchanged_name: + return "the replacement equals the current spelling"; + case navigation::Refusal::multi_file_without_transaction: + return "multi-file rename requires client transaction support"; + case navigation::Refusal::none: + break; + } + return "navigation refused"; +} + +int symbol_kind(index::SymbolKind kind) { + switch (kind) { + case index::SymbolKind::function: + return 12; // LSP Function + case index::SymbolKind::type: + return 5; // LSP Class + case index::SymbolKind::variable: + return 13; // LSP Variable + case index::SymbolKind::field: + return 8; // LSP Field + case index::SymbolKind::namespace_: + return 3; // LSP Namespace + case index::SymbolKind::module: + return 2; // LSP Module + case index::SymbolKind::unknown: + break; + } + return 1; // LSP File fallback for an unclassified symbol +} + +struct EditorReport { + Json::Array diagnostics, other_messages; + std::size_t unlocated{}; +}; + +EditorReport for_owner(const DiagnosticBatch &batch) { + EditorReport report; + for (const auto &d : batch.diagnostics) { + if (!d.location.range || !d.location.snapshot || + !d.location.snapshot->same_input_as(*batch.owner)) { + ++report.unlocated; + if (report.other_messages.size() < 8) + report.other_messages.emplace_back(d.message.substr(0, 1024)); + continue; + } + auto &r = *d.location.range; + Json::Object item{ + {"range", Json{Json::Object{{"start", position(r.start)}, {"end", position(r.end)}}}}, + {"severity", Json{static_cast(d.severity) + 1}}, + {"source", Json{std::string{"gcc"}}}, + {"message", Json{d.message}}}; + if (!d.rule.empty()) + item.emplace("code", Json{d.rule}); + report.diagnostics.emplace_back(std::move(item)); + } + return report; +} + +std::expected +notification(std::string_view uri, std::optional version, Json::Array diagnostics) { + Json::Object params{{"uri", Json{std::string{uri}}}, + {"diagnostics", Json{std::move(diagnostics)}}}; + if (version) + params.emplace("version", Json{std::int64_t{*version}}); + return P::serialize_json( + Json{Json::Object{{"jsonrpc", Json{std::string{"2.0"}}}, + {"method", Json{std::string{"textDocument/publishDiagnostics"}}}, + {"params", Json{std::move(params)}}}}); +} + +struct Receipt { + SemanticContextLease lease; + SourceScope scope; + std::shared_ptr capture; +}; + +struct Entry { + std::string uri, state{"queued"}, detail, provider, alternative; + std::optional version, published_version; + bool sent{}, had_findings{}; + std::shared_ptr receipt; + std::shared_ptr> occurrences; + std::string occurrence_state{"disabled"}, occurrence_reason; + std::string module_state{"disabled"}, module_detail; + std::string module_artifact_state{"disabled"}, module_artifact_detail, + module_artifact_generation; + std::vector module_provides, module_imports; + std::vector hints; + B::Selection hint_selection; + std::size_t runs{}, unlocated{}; + Json::Array other_messages; + std::optional retry_at; + std::chrono::seconds retry_delay{1}; +}; +} // namespace + +struct EditorDiagnostics::State { + fs::path root; + std::shared_ptr profile; + WorkspaceSession &workspace; + const Documents::DocumentStore &documents; + SourceCatalog catalog; + Send send; + std::mutex mutex; + std::condition_variable wake; + std::map entries; + std::deque pending; + // One foreground slot: the analysis worker is still the single owner of compiler + // process state, grants and the module cache. The scheduler supplies bounded + // admission, revision coalescing, cancellation, a running watchdog and metrics. + scheduler::Scheduler scheduler; + modules::ModuleWorkQueue module_work{scheduler}; + index::SymbolIndex symbols; + bool updating{}, stopped{}, versions{}, transactional_rename{}; + std::uint64_t epoch{1}, issued{}; + Clock::time_point earliest{}, next_poll{Clock::now() + 1s}; + // The single worker installs source grants and owns the process for each job. + std::optional scope; + InstalledSourceGrant grant; + fs::path artifact_root; + std::shared_ptr artifacts; + std::jthread worker; + + State(fs::path r, std::shared_ptr p, WorkspaceSession &w, + const Documents::DocumentStore &d, Send output) + : root(std::move(r)), profile(std::move(p)), workspace(w), documents(d), catalog(d), + send(std::move(output)), scheduler(scheduler::Budget{.foreground = 1, + .background = 1, + .artifact = 1, + .queued = 32, + .memory_mib = 4096, + .watchdog = 90s}), + worker([this] { loop(); }) {} + + fs::path artifact_root_of() { + if (artifact_root.empty()) + artifact_root = + fs::temp_directory_path() / ("vls-module-artifacts-" + std::to_string(::getpid())); + return artifact_root; + } + + bool current(const std::string &key, std::uint64_t generation) const { + return !stopped && !updating && generation == epoch && entries.contains(key); + } + void retract(Entry &entry, bool closed = false) { + if (entry.sent && (entry.had_findings || closed)) { + auto body = + notification(entry.uri, versions ? entry.published_version : std::nullopt, {}); + if (body) + send(std::move(*body)); + } + entry.sent = false; + entry.had_findings = false; + } + void queue(const std::string &key, Entry &entry) { + entry.state = "queued"; + entry.detail.clear(); + entry.other_messages.clear(); + entry.unlocated = entry.runs = 0; + entry.receipt.reset(); + entry.occurrences.reset(); + entry.occurrence_state = "disabled"; + entry.occurrence_reason.clear(); + entry.module_state = "disabled"; + entry.module_detail.clear(); + entry.module_provides.clear(); + entry.module_imports.clear(); + entry.module_artifact_state = "disabled"; + entry.module_artifact_detail.clear(); + entry.module_artifact_generation.clear(); + entry.retry_at.reset(); + symbols.remove(key); + pending.push_back(key); + } + void failed(const std::string &key, std::uint64_t generation, std::string reason, + bool refresh_context = false) { + std::lock_guard lock{mutex}; + if (!current(key, generation)) + return; + auto &entry = entries.at(key); + retract(entry); + entry.receipt.reset(); + entry.occurrences.reset(); + entry.state = "unavailable"; + entry.detail = std::move(reason); + if (refresh_context) { + entry.retry_at = Clock::now() + entry.retry_delay; + entry.retry_delay = std::min(entry.retry_delay * 2, 30s); + } + } + bool valid(const Receipt &record) const { + return workspace.validate_semantic_context(record.lease) && + catalog.validate(record.scope, *record.capture); + } + void analyze(const std::string &key, std::uint64_t generation, std::uint64_t sequence, + std::stop_token cancel) { + auto lease = workspace.acquire_semantic_context(key, std::nullopt, + {profile->driver, W::CompilerDriver::gcc}); + if (!lease) + return failed(key, generation, lease.error().message, true); + const auto &selection = lease->selection(); + SourceScope job{selection->generation->identity().workspace, + lease->configuration_generation(), lease->driver().tool.trust_generation}; + auto owner = documents.snapshot(key); + if (job.workspace.root != root || !owner || !selection->selected || + owner->identity.canonical_path != selection->selected->key.owning_tu) + return failed(key, generation, + "The selected command belongs to another translation unit or workspace"); + if (!scope || *scope != job) { + auto installed = catalog.install(job, std::array{root}); + if (!installed) + return failed(key, generation, "Could not bind the workspace source directory"); + scope = job; + grant = std::move(*installed); + } + std::vector warm; + { + std::lock_guard lock{mutex}; + if (!current(key, generation)) + return; + auto &entry = entries.at(key); + if (entry.hint_selection == selection) + warm = entry.hints; + } + if (cancel.stop_requested() || !workspace.validate_semantic_context(*lease)) + return failed(key, generation, "The compiler command was superseded", true); + auto result = + analyze_with_gcc(*profile, *lease, documents, catalog, grant, sequence, warm, cancel); + // Old lookup hints may include a file removed by the edit. Discover the current + // program from its TU when the old namespace cannot be materialized. + if (!result && !warm.empty() && !cancel.stop_requested() && + workspace.validate_semantic_context(*lease)) + result = + analyze_with_gcc(*profile, *lease, documents, catalog, grant, sequence, {}, cancel); + if (!result) + return failed(key, generation, result.error()); + auto receipt = std::make_shared(Receipt{*lease, job, result->sources}); + auto report = for_owner(result->batch); + const bool has_findings = !report.diagnostics.empty(); + const bool publish = + has_findings || (result->batch.complete_for_owner && !report.unlocated); + // Bind the reply to this exact selection and diagnostics operation before delivery. + B::PublicationSlot slot{lease->selection_state(), B::Operation::diagnostics}; + auto accepted = slot.replace_inputs(sequence, result->revision); + auto ticket = slot.issue(); + if (!accepted || !ticket || !valid(*receipt) || !owner->same_input_as(*result->batch.owner)) + return failed(key, generation, "The compiler inputs changed before publication", true); + std::unique_lock lock{mutex}; + if (!current(key, generation)) + return; + auto &entry = entries.at(key); + if (publish) { + auto body = notification(entry.uri, versions ? owner->version : std::nullopt, + std::move(report.diagnostics)); + if (!body || !slot.publish(*ticket, *body) || !send(std::move(*body))) { + entry.state = "unavailable"; + entry.detail = "Could not publish the compiler diagnostics"; + return; + } + entry.sent = true; + entry.had_findings = has_findings; + entry.published_version = owner->version; + } else + retract(entry); + entry.provider = selection->generation->identity().provider; + entry.alternative = selection->selected->key.alternative; + entry.hint_selection = selection; + entry.hints = std::move(result->lookups); + entry.runs = result->compiler_runs; + entry.unlocated = report.unlocated; + entry.other_messages = std::move(report.other_messages); + entry.receipt = std::move(receipt); + if (result->occurrences) { + entry.occurrences = std::make_shared>( + std::move(result->occurrences->occurrences)); + entry.occurrence_state = !result->occurrences->complete + ? "incomplete" + : (result->occurrences->partial ? "partial" : "ready"); + entry.occurrence_reason = result->occurrences->reason; + } else { + entry.occurrences.reset(); + entry.occurrence_state = profile->observes() ? "unavailable" : "disabled"; + entry.occurrence_reason = result->occurrence_detail; + } + entry.retry_delay = 1s; + index::ContextInput facts; + facts.context = key; + facts.complete = + result->occurrences && result->occurrences->complete && !result->occurrences->partial; + facts.reason = + result->occurrences ? result->occurrences->reason : result->occurrence_detail; + for (const auto &source : result->sources->entries()) + if (source.snapshot) { + facts.sources.emplace_back(source.logical_path.native(), + source.snapshot->content_hash.sha256_hex); + facts.dependencies.push_back(source.logical_path.native()); + } + if (entry.occurrences) + for (const auto &occurrence : *entry.occurrences) { + index::SymbolRecord record; + record.name = occurrence.name; + record.kind = index::SymbolKind::function; + record.location = location_of(occurrence.use, *occurrence.use_file); + if (occurrence.has_definition()) + record.definition = + location_of(occurrence.definition, *occurrence.definition_file); + record.provenance = "stock-observer"; + facts.records.push_back(std::move(record)); + } + symbols.publish(facts); + // The index is current before the status advertises readiness. + entry.state = result->batch.complete_for_owner && !report.unlocated ? "ready" : "partial"; + entry.module_state = "running"; + entry.module_detail.clear(); + entry.module_provides.clear(); + entry.module_imports.clear(); + entry.module_artifact_state = "disabled"; + entry.module_artifact_detail.clear(); + entry.module_artifact_generation.clear(); + std::vector scan_hints = entry.hints; + std::vector artifact_arguments; + const auto working_directory = *selection->selected->working_directory; + const auto &translation_unit = selection->selected->key.owning_tu; + if (selection->selected->semantic_arguments && + !selection->selected->semantic_arguments->empty()) { + const auto &original = *selection->selected->semantic_arguments; + artifact_arguments.push_back(original.front()); + for (std::size_t i = 1; i < original.size(); ++i) { + const auto &argument = original[i]; + if (argument == "-c" || argument == translation_unit.native()) + continue; + if (argument == "-o") { + ++i; + continue; + } + artifact_arguments.push_back(argument); + } + artifact_arguments.insert( + artifact_arguments.end(), + {"-fmodules-ts", "-c", translation_unit.native(), "-o", "module.o"}); + } + lock.unlock(); + auto product = std::make_shared(); + const auto scan_lease = *lease; + const auto scan_grant = grant; + const auto scan_profile = profile; + const bool admitted = module_work.submit( + key, modules::ModuleWorkKind::scan, sequence, + [this, scan_lease, scan_grant, scan_profile, product, + scan_hints = std::move(scan_hints)](std::stop_token token) { + auto scanned = scan_modules_with_gcc(*scan_profile, scan_lease, documents, catalog, + scan_grant, scan_hints, token); + if (!scanned) + throw std::runtime_error(scanned.error()); + *product = std::move(*scanned); + return std::string{}; + }, + [this, key, generation, product, artifact_arguments, + working_directory](modules::ModuleTaskResult task) { + { + std::lock_guard guard{mutex}; + if (!current(key, generation)) + return; + auto &finished = entries.at(key); + finished.module_state = + task.outcome == scheduler::Outcome::completed + ? (product->complete ? "ready" : "partial") + : (task.outcome == scheduler::Outcome::cancelled ? "cancelled" + : "failed"); + finished.module_detail = task.detail; + finished.module_provides = product->provides; + finished.module_imports = product->imports; + } + if (task.outcome != scheduler::Outcome::completed || product->provides.empty() || + artifact_arguments.empty()) + return; + std::shared_ptr cache; + fs::path artifact_root; + { + std::lock_guard guard{mutex}; + if (!artifacts) + artifacts = std::make_shared(artifact_root_of()); + cache = artifacts; + artifact_root = this->artifact_root; + } + const auto generation_id = std::make_shared(); + module_work.submit( + key, modules::ModuleWorkKind::artifact, task.revision, + [cache, artifact_arguments, working_directory, generation_id, product, + artifact_root](std::stop_token) { + modules::ModulePlan plan; + plan.domain.compatibility = "stock-gcc-16.2.0"; + plan.claims_complete = true; + for (const auto &name : product->provides) { + B::ContextKey context{{}, + {}, + B::ContextRole::target, + name, + working_directory / (name + ".cpp")}; + modules::UnitInputs inputs{"artifact-" + name, name, name, {}}; + plan.units.push_back({{context, + {working_directory, name + ".o"}, + inputs, + "editor-scan", + {}}, + modules::UnitKind::primary_interface, + {}}); + plan.order.push_back(context); + } + modules::ModuleCommand command{working_directory, artifact_arguments}; + auto produced = modules::produce_module_artifacts( + plan, *cache, artifact_root / "staging", + modules::gcc_module_artifact_work( + [command](const B::ContextKey &) + -> std::optional { return command; })); + if (!produced) + throw std::runtime_error(produced.error()); + *generation_id = (*produced)->id(); + return *generation_id; + }, + [this, key, generation, generation_id](modules::ModuleTaskResult task) { + std::lock_guard guard{mutex}; + if (!current(key, generation)) + return; + auto &finished = entries.at(key); + finished.module_artifact_state = + task.outcome == scheduler::Outcome::completed + ? "ready" + : (task.outcome == scheduler::Outcome::cancelled ? "cancelled" + : "failed"); + finished.module_artifact_detail = task.detail; + finished.module_artifact_generation = *generation_id; + }); + std::lock_guard guard{mutex}; + if (current(key, generation)) + entries.at(key).module_artifact_state = "running"; + }); + if (!admitted) { + std::lock_guard guard{mutex}; + if (current(key, generation)) { + auto &refused = entries.at(key); + refused.module_state = "unavailable"; + refused.module_detail = "module scan admission was refused"; + } + } + } + + void poll(std::unique_lock &lock) { + const auto generation = epoch; + std::vector>> saved; + for (auto &[key, entry] : entries) + if (entry.receipt) + saved.emplace_back(key, entry.receipt); + else if (entry.retry_at && Clock::now() >= *entry.retry_at) + queue(key, entry); + for (auto &[key, receipt] : saved) { + lock.unlock(); + const bool still_valid = valid(*receipt); + lock.lock(); + if (!current(key, generation)) + return; + auto &entry = entries.at(key); + if (!still_valid && entry.receipt == receipt) { + retract(entry); + queue(key, entry); + } + } + } + navigation::FactSet fact_set_locked() const { + navigation::FactSet set; + set.backend = "stock GCC 16.2.0"; + set.generation = symbols.generation(); + for (const auto &[key, entry] : entries) { + set.contexts.push_back( + {key, entry.occurrence_state == "ready", entry.occurrence_reason}); + if (entry.occurrences) + for (const auto &occurrence : *entry.occurrences) { + navigation::Fact fact; + fact.binding.name = occurrence.name; + if (occurrence.has_definition()) + fact.binding.definition = navigation::Location{ + occurrence.definition_file->identity.canonical_path.native(), + {occurrence.definition.start.line, + occurrence.definition.start.character, occurrence.definition.end.line, + occurrence.definition.end.character}}; + fact.context = key; + fact.source = occurrence.use_file->identity.canonical_path.native(); + fact.content = occurrence.use_file->content_hash.sha256_hex; + fact.use = {occurrence.use.start.line, occurrence.use.start.character, + occurrence.use.end.line, occurrence.use.end.character}; + fact.editable = under(root, fact.source); + fact.provenance = "stock-observer"; + set.facts.push_back(std::move(fact)); + } + if (entry.receipt) + for (const auto &source : entry.receipt->capture->entries()) + if (source.snapshot) + set.current_sources[source.logical_path.native()] = + source.snapshot->content_hash.sha256_hex; + } + // Index-backed coverage: persisted contexts and overlays join the set. + // Facts whose source content is not currently known stay non-editable, + // so a rename can never edit an unverified file. + if (const auto generation = symbols.current()) { + std::vector sources; + sources.reserve(set.current_sources.size()); + for (const auto &[path, content] : set.current_sources) + sources.push_back({path, content, under(root, path)}); + features::ingest_index_facts(set, *generation, sources); + } + return set; + } + + void loop() { + std::unique_lock lock{mutex}; + while (!stopped) { + if (updating) { + wake.wait(lock, [&] { return stopped || !updating; }); + continue; + } + if (pending.empty()) { + if (Clock::now() < next_poll) { + wake.wait_until(lock, next_poll); + continue; + } + next_poll = Clock::now() + 1s; + poll(lock); + continue; + } + if (Clock::now() < earliest) { + wake.wait_until(lock, earliest); + continue; + } + auto key = std::move(pending.front()); + pending.pop_front(); + const auto generation = epoch, sequence = ++issued; + entries.at(key).state = "running"; + lock.unlock(); + const bool accepted = scheduler.submit( + {.priority = scheduler::Priority::foreground, + .key = key, + .revision = sequence, + .memory_mib = 1}, + [this, key, generation, sequence](std::stop_token cancel) { + try { + analyze(key, generation, sequence, cancel); + } catch (const std::exception &) { + failed(key, generation, "The compiler job could not be completed"); + } + return std::string{}; + }, + [this, key, generation](scheduler::Result result) { + if (result.outcome != scheduler::Outcome::timed_out) + return; + std::lock_guard guard{mutex}; + if (!current(key, generation)) + return; + auto &entry = entries.at(key); + retract(entry); + entry.receipt.reset(); + entry.occurrences.reset(); + entry.state = "unavailable"; + entry.detail = "The compiler job exceeded its deadline"; + entry.retry_at = Clock::now() + entry.retry_delay; + entry.retry_delay = std::min(entry.retry_delay * 2, 30s); + }); + lock.lock(); + if (!accepted && current(key, generation)) { + auto &entry = entries.at(key); + entry.state = "unavailable"; + entry.detail = "The analysis queue is full"; + entry.retry_at = Clock::now() + entry.retry_delay; + entry.retry_delay = std::min(entry.retry_delay * 2, 30s); + } + } + } +}; + +EditorDiagnostics::EditorDiagnostics(const fs::path &root, + std::shared_ptr profile, + WorkspaceSession &workspace, + const Documents::DocumentStore &documents, Send send) + : state_(std::make_unique(root, std::move(profile), workspace, documents, + std::move(send))) {} +EditorDiagnostics::~EditorDiagnostics() { stop(); } +void EditorDiagnostics::set_version_support(bool enabled) { + std::lock_guard lock{state_->mutex}; + state_->versions = enabled; +} +void EditorDiagnostics::begin_update() { + auto &s = *state_; + std::vector active; + { + std::lock_guard lock{s.mutex}; + ++s.epoch; + s.updating = true; + s.pending.clear(); + active.reserve(s.entries.size()); + for (const auto &[key, entry] : s.entries) + active.push_back(key); + } + // Cancellation may invoke a terminal completion synchronously, so it runs + // without the state lock. A queued job is cancelled immediately; a running + // job receives a cooperative stop request. + for (const auto &key : active) { + s.scheduler.cancel(key); + s.module_work.cancel(key); + } +} +void EditorDiagnostics::finish_update(bool workspace_changed) { + auto &s = *state_; + auto overlays = s.documents.list_overlays(); + std::lock_guard lock{s.mutex}; + if (s.stopped) + return; + std::set present; + for (const auto &overlay : overlays) { + const auto &id = overlay->identity; + if (!id.is_file_uri || !overlay->version || + std::mismatch(s.root.begin(), s.root.end(), id.canonical_path.begin(), + id.canonical_path.end()) + .first != s.root.end()) + continue; + present.insert(id.canonical_uri); + } + for (auto i = s.entries.begin(); i != s.entries.end();) { + if (present.contains(i->first)) + ++i; + else { + s.retract(i->second, true); + s.symbols.remove(i->first); + s.module_work.cancel(i->first); + i = s.entries.erase(i); + } + } + for (const auto &overlay : overlays) { + const auto &id = overlay->identity; + if (!present.contains(id.canonical_uri) || + (s.entries.size() >= max_documents && !s.entries.contains(id.canonical_uri))) + continue; + auto &entry = s.entries[id.canonical_uri]; + entry.uri = id.display_uri; + entry.version = overlay->version; + entry.retry_delay = 1s; + if (workspace_changed) { + s.retract(entry); + entry.hints.clear(); + entry.hint_selection.reset(); + } + s.queue(id.canonical_uri, entry); + } + s.earliest = Clock::now() + 75ms; + s.updating = false; + s.wake.notify_one(); +} +void EditorDiagnostics::stop() { + auto &s = *state_; + { + std::lock_guard lock{s.mutex}; + s.stopped = true; + s.wake.notify_one(); + } + s.scheduler.cancel_all(); + s.module_work.cancel_all(); + if (s.worker.joinable()) + s.worker.join(); +} +Json EditorDiagnostics::status(std::string_view uri) const { + auto &s = *state_; + auto key = Documents::client_uri_key(uri); + std::lock_guard lock{s.mutex}; + const auto i = key ? s.entries.find(*key) : s.entries.end(); + if (i == s.entries.end()) + return Json{Json::Object{ + {"state", Json{std::string{"unavailable"}}}, + {"detail", + Json{std::string{"No synchronized document is scheduled for this workspace"}}}}}; + const auto &entry = i->second; + Json::Object result{{"uri", Json{entry.uri}}, + {"state", Json{entry.state}}, + {"backend", Json{std::string{"GCC 16.2.0"}}}, + {"detail", Json{entry.detail}}, + {"compilerRuns", Json{static_cast(entry.runs)}}, + {"unlocatedCount", Json{static_cast(entry.unlocated)}}, + {"messages", Json{entry.other_messages}}}; + if (entry.version) + result.emplace("version", Json{std::int64_t{*entry.version}}); + if (entry.receipt) { + result.emplace("provider", Json{entry.provider}); + result.emplace("alternative", Json{entry.alternative}); + result.emplace("workspaceUri", Json{Documents::path_to_file_uri(s.root)}); + result.emplace("projectCoverage", Json{std::string{"selectedTranslationUnit"}}); + Json::Array provides, imports; + for (const auto &name : entry.module_provides) + provides.push_back(Json{name}); + for (const auto &name : entry.module_imports) + imports.push_back(Json{name}); + result.emplace("moduleArtifact", + Json{Json::Object{{"state", Json{entry.module_artifact_state}}, + {"detail", Json{entry.module_artifact_detail}}, + {"generation", Json{entry.module_artifact_generation}}}}); + result.emplace("moduleScan", Json{Json::Object{{"state", Json{entry.module_state}}, + {"detail", Json{entry.module_detail}}, + {"provides", Json{std::move(provides)}}, + {"imports", Json{std::move(imports)}}}}); + result.emplace( + "occurrences", + Json{Json::Object{{"state", Json{entry.occurrence_state}}, + {"count", Json{static_cast( + entry.occurrences ? entry.occurrences->size() : 0)}}, + {"reason", Json{entry.occurrence_reason}}}}); + } + const auto coverage = s.symbols.coverage(); + result.emplace( + "index", + Json{Json::Object{{"generation", Json{static_cast(s.symbols.generation())}}, + {"records", Json{static_cast(s.symbols.records())}}, + {"indexed", Json{coverage.indexed}}, + {"complete", Json{coverage.complete}}}}); + const auto metrics = s.scheduler.metrics(); + result.emplace( + "scheduler", + Json{Json::Object{ + {"accepted", Json{static_cast(metrics.accepted)}}, + {"completed", Json{static_cast(metrics.completed)}}, + {"failed", Json{static_cast(metrics.failed)}}, + {"cancelled", Json{static_cast(metrics.cancelled)}}, + {"timedOut", Json{static_cast(metrics.timed_out)}}, + {"queuedPeak", Json{static_cast(metrics.queued_peak)}}, + {"runningPeak", Json{static_cast(metrics.running_peak)}}, + {"queueMs", Json{static_cast(metrics.queue_nanoseconds / 1'000'000)}}, + {"runMs", Json{static_cast(metrics.run_nanoseconds / 1'000'000)}}}}); + return Json{std::move(result)}; +} + +namespace { +const Occurrence *covering(const Receipt &receipt, const std::vector &facts, + const std::string &key, Documents::Position position) { + const Documents::DocumentSnapshot *snapshot = nullptr; + for (const auto &entry : receipt.capture->entries()) + if (entry.snapshot && entry.snapshot->identity.canonical_uri == key) { + snapshot = entry.snapshot.get(); + break; + } + if (!snapshot) + return nullptr; + const auto offset = snapshot->position_to_offset(position); + if (!offset) + return nullptr; + for (const auto &fact : facts) { + if (fact.use_file.get() != snapshot) + continue; + const auto range = snapshot->range_to_offsets(fact.use); + if (range && *offset >= range->first && *offset <= range->second) + return &fact; + } + return nullptr; +} +} // namespace + +bool EditorDiagnostics::supports_occurrences() const noexcept { + return state_->profile->observes(); +} + +Json EditorDiagnostics::workspace_symbols(std::string_view query) const { + index::Query selected; + selected.name = std::string{query.substr(0, 256)}; + selected.substring = true; + selected.limit = 100; + const auto result = state_->symbols.find(selected); + Json::Array symbols; + for (const auto &record : result.symbols) { + const auto &location = record.definition ? *record.definition : record.location; + symbols.push_back(Json{Json::Object{ + {"name", Json{record.name}}, + {"kind", Json{static_cast(symbol_kind(record.kind))}}, + {"location", Json{Json::Object{ + {"uri", Json{Documents::path_to_file_uri(location.path)}}, + {"range", Json{Json::Object{ + {"start", position({location.line, location.character})}, + {"end", position({location.endLine, + location.endCharacter})}}}}}}}}}); + } + return Json{std::move(symbols)}; +} + +Json EditorDiagnostics::completion(std::string_view uri, Documents::Position position) const { + auto &s = *state_; + const auto snapshot = s.documents.snapshot(uri); + if (!snapshot) + return Json{nullptr}; + const auto offset = snapshot->position_to_offset(position); + if (!offset) + return Json{nullptr}; + const auto text = std::string_view{snapshot->text}; + const auto prefix = features::completion::prefix_at(text, *offset); + index::Query query; + query.name = std::string{prefix}; + query.substring = true; + query.limit = 200; + std::vector candidates; + { + std::lock_guard lock{s.mutex}; + const auto result = s.symbols.find(query); + for (const auto &record : result.symbols) { + const auto kind = + record.kind == index::SymbolKind::function ? features::completion::Kind::function + : record.kind == index::SymbolKind::type ? features::completion::Kind::type + : record.kind == index::SymbolKind::variable ? features::completion::Kind::variable + : record.kind == index::SymbolKind::field ? features::completion::Kind::field + : record.kind == index::SymbolKind::namespace_ + ? features::completion::Kind::namespace_ + : record.kind == index::SymbolKind::module ? features::completion::Kind::module + : features::completion::Kind::unknown; + candidates.push_back({record.name, + kind, + record.location.path, + record.provenance, + {record.name, record.location.path, record.location.line, + record.location.character}}); + } + } + const std::uint64_t generation = s.symbols.generation(); + const auto completed = features::completion::complete(candidates, text, *offset); + Json::Array items; + for (const auto &item : completed.items) { + items.push_back(Json{Json::Object{ + {"label", Json{item.label}}, + {"kind", Json{static_cast(item.kind)}}, + {"detail", Json{item.detail}}, + {"sortText", Json{item.sort_text}}, + {"data", Json{Json::Object{ + {"generation", Json{static_cast(generation)}}, + {"name", Json{item.identity.name}}, + {"path", Json{item.identity.path}}, + {"line", Json{static_cast(item.identity.line)}}, + {"character", Json{static_cast(item.identity.character)}}}}}, + {"textEdit", + Json{Json::Object{ + {"range", range_json(Documents::Range{ + {position.line, static_cast(item.replacement_start)}, + {position.line, static_cast(item.replacement_end)}})}, + {"newText", Json{item.label}}}}}}}); + } + return Json{Json::Object{{"isIncomplete", Json{completed.incomplete}}, + {"items", Json{std::move(items)}}}}; +} + +Json EditorDiagnostics::completion_resolve(const Json &item) const { + auto &s = *state_; + const auto *fields = P::as_object(&item); + if (!fields) + return item; + const auto *data = P::as_object(P::find_member(*fields, "data")); + if (!data) + return item; + const auto *name = P::as_string(P::find_member(*data, "name")); + const auto *path = P::as_string(P::find_member(*data, "path")); + const auto generation = P::as_int64(P::find_member(*data, "generation")); + const auto line = P::as_int64(P::find_member(*data, "line")); + const auto character = P::as_int64(P::find_member(*data, "character")); + if (!name || !path || !generation || !line || !character || *line < 0 || *character < 0) + return item; + features::completion::Identity identity{*name, *path, static_cast(*line), + static_cast(*character)}; + std::vector current; + std::uint64_t now{}; + { + std::lock_guard lock{s.mutex}; + now = s.symbols.generation(); + index::Query query; + query.name = *name; + query.limit = 64; + const auto result = s.symbols.find(query); + for (const auto &record : result.symbols) { + const auto kind = + record.kind == index::SymbolKind::function ? features::completion::Kind::function + : record.kind == index::SymbolKind::type ? features::completion::Kind::type + : record.kind == index::SymbolKind::variable ? features::completion::Kind::variable + : record.kind == index::SymbolKind::field ? features::completion::Kind::field + : record.kind == index::SymbolKind::namespace_ + ? features::completion::Kind::namespace_ + : record.kind == index::SymbolKind::module ? features::completion::Kind::module + : features::completion::Kind::unknown; + features::completion::Detail detail; + detail.identity = {record.name, record.location.path, record.location.line, + record.location.character}; + detail.kind = kind; + detail.detail = record.location.path; + detail.provenance = record.provenance; + current.push_back(std::move(detail)); + } + } + const auto resolved = features::completion::resolve( + identity, static_cast(*generation), now, current); + if (resolved.status != features::completion::Resolved::Status::resolved) + return item; + Json::Object enriched = *fields; + enriched.insert_or_assign("detail", Json{resolved.detail}); + Json::Object documentation; + documentation.emplace("kind", Json{std::string{"markdown"}}); + documentation.emplace("value", Json{resolved.documentation}); + enriched.insert_or_assign("documentation", Json{std::move(documentation)}); + return Json{std::move(enriched)}; +} + +void EditorDiagnostics::set_transactional_rename(bool supported) { + std::lock_guard lock{state_->mutex}; + state_->transactional_rename = supported; +} + +EditorDiagnostics::NavigationReply +EditorDiagnostics::references(std::string_view uri, Documents::Position position) const { + auto &s = *state_; + std::lock_guard lock{s.mutex}; + const auto identity = Documents::normalize_uri(uri); + if (!identity || !identity->is_file_uri) + return {Json{nullptr}, "invalid document URI"}; + const auto path = identity->canonical_path.native(); + const auto set = s.fact_set_locked(); + const auto binding = navigation::binding_at(set, path, {position.line, position.character}); + if (!binding) + return {Json{nullptr}, refusal_text(binding.error())}; + const auto result = navigation::references(set, *binding); + Json::Array locations; + for (const auto &location : result.locations) + locations.push_back(Json{Json::Object{ + {"uri", Json{Documents::path_to_file_uri(location.path)}}, + {"range", range_json(Documents::Range{ + {location.range.start.line, location.range.start.character}, + {location.range.end.line, location.range.end.character}})}}}); + auto value = Json{std::move(locations)}; + if (!result.coverage_complete) { + std::string detail = "incomplete reference coverage"; + for (const auto &context : result.incomplete_contexts) + detail += (detail.empty() ? "" : ", ") + context; + return {std::move(value), std::move(detail)}; + } + return {std::move(value), std::nullopt}; +} + +EditorDiagnostics::NavigationReply +EditorDiagnostics::prepare_rename(std::string_view uri, Documents::Position position) const { + auto &s = *state_; + std::lock_guard lock{s.mutex}; + const auto identity = Documents::normalize_uri(uri); + if (!identity || !identity->is_file_uri) + return {Json{nullptr}, "invalid document URI"}; + const auto path = identity->canonical_path.native(); + const auto set = s.fact_set_locked(); + const auto binding = navigation::binding_at(set, path, {position.line, position.character}); + if (!binding) + return {Json{nullptr}, refusal_text(binding.error())}; + const auto plan = navigation::prepare_rename(set, path, {position.line, position.character}, + binding->name + "_", s.transactional_rename); + if (plan.refusal == navigation::Refusal::incomplete_coverage || + plan.refusal == navigation::Refusal::stale_source || + plan.refusal == navigation::Refusal::non_editable_origin || + plan.refusal == navigation::Refusal::ambiguous_binding) + return {Json{nullptr}, refusal_text(plan.refusal)}; + const auto fact = std::ranges::find_if(set.facts, [&](const auto &candidate) { + return candidate.binding == *binding && candidate.source == path && + candidate.use.start.line <= position.line && position.line <= candidate.use.end.line; + }); + if (fact == set.facts.end()) + return {Json{nullptr}, refusal_text(navigation::Refusal::unknown_binding)}; + return {Json{Json::Object{{"range", range_json(Documents::Range{ + {fact->use.start.line, fact->use.start.character}, + {fact->use.end.line, fact->use.end.character}})}, + {"placeholder", Json{fact->binding.name}}}}, + std::nullopt}; +} + +EditorDiagnostics::NavigationReply EditorDiagnostics::rename(std::string_view uri, + Documents::Position position, + std::string_view replacement) const { + auto &s = *state_; + std::lock_guard lock{s.mutex}; + const auto identity = Documents::normalize_uri(uri); + if (!identity || !identity->is_file_uri) + return {Json{nullptr}, "invalid document URI"}; + const auto path = identity->canonical_path.native(); + const auto set = s.fact_set_locked(); + const auto plan = navigation::prepare_rename(set, path, {position.line, position.character}, + replacement, s.transactional_rename); + if (!plan.ready()) + return {Json{nullptr}, refusal_text(plan.refusal) + ": " + plan.detail}; + Json::Object changes; + for (const auto &edit : plan.edits) { + auto uri_key = Documents::path_to_file_uri(edit.path); + auto &entry = changes[uri_key]; + if (!std::holds_alternative(entry.value)) + entry = Json{Json::Array{}}; + std::get(entry.value) + .push_back(Json{Json::Object{ + {"range", + range_json(Documents::Range{{edit.range.start.line, edit.range.start.character}, + {edit.range.end.line, edit.range.end.character}})}, + {"newText", Json{edit.replacement}}}}); + } + return {Json{Json::Object{{"changes", Json{std::move(changes)}}}}, std::nullopt}; +} + +Json EditorDiagnostics::hover(std::string_view uri, Documents::Position position) const { + auto &s = *state_; + auto key = Documents::client_uri_key(uri); + std::shared_ptr receipt; + std::shared_ptr> facts; + { + std::lock_guard lock{s.mutex}; + const auto i = key ? s.entries.find(*key) : s.entries.end(); + if (i == s.entries.end()) + return Json{nullptr}; + receipt = i->second.receipt; + facts = i->second.occurrences; + } + if (!receipt || !facts || !s.valid(*receipt)) + return Json{nullptr}; + const auto *match = covering(*receipt, *facts, *key, position); + if (!match) + return Json{nullptr}; + std::string text = + match->signature.empty() ? match->name + ": " + match->type : match->signature; + text += "\n" + match->canonical_type; + return Json{ + Json::Object{{"contents", Json{Json::Object{{"kind", Json{std::string{"plaintext"}}}, + {"value", Json{std::move(text)}}}}}, + {"range", range_json(match->use)}}}; +} + +Json EditorDiagnostics::signature_help(std::string_view uri, Documents::Position position) const { + auto &s = *state_; + auto key = Documents::client_uri_key(uri); + std::shared_ptr receipt; + std::shared_ptr> facts; + { + std::lock_guard lock{s.mutex}; + const auto i = key ? s.entries.find(*key) : s.entries.end(); + if (i == s.entries.end()) + return Json{nullptr}; + receipt = i->second.receipt; + facts = i->second.occurrences; + } + if (!receipt || !facts || !s.valid(*receipt)) + return Json{nullptr}; + const Documents::DocumentSnapshot *snapshot = nullptr; + for (const auto &entry : receipt->capture->entries()) + if (entry.snapshot && entry.snapshot->identity.canonical_uri == *key) { + snapshot = entry.snapshot.get(); + break; + } + if (!snapshot) + return Json{nullptr}; + const auto offset = snapshot->position_to_offset(position); + if (!offset) + return Json{nullptr}; + // The occurrence span covers the callee name only, so the innermost call + // whose argument list contains the cursor is selected explicitly. + const Occurrence *match = nullptr; + std::size_t match_start{}; + for (const auto &fact : *facts) { + if (fact.use_file.get() != snapshot || fact.signature.empty()) + continue; + const auto use = snapshot->range_to_offsets(fact.use); + if (!use) + continue; + if (!features::signature::in_call(snapshot->text, use->first, use->second, *offset)) + continue; + if (!match || use->first > match_start) { + match = &fact; + match_start = use->first; + } + } + if (!match) + return Json{nullptr}; + const std::vector signatures{match->signature}; + const auto help = features::signature::build(signatures, snapshot->text, *offset); + if (help.signatures.empty()) + return Json{nullptr}; + Json::Array rendered; + for (const auto &signature : help.signatures) { + Json::Array parameters; + for (const auto ¶meter : signature.parameters) { + parameters.push_back(Json{Json::Object{ + {"label", + parameter.range + ? Json{Json::Array{Json{static_cast(parameter.range->first)}, + Json{static_cast(parameter.range->second)}}} + : Json{parameter.label}}}}); + } + rendered.push_back(Json{Json::Object{{"label", Json{signature.label}}, + {"parameters", Json{std::move(parameters)}}}}); + } + return Json{ + Json::Object{{"signatures", Json{std::move(rendered)}}, + {"activeSignature", Json{static_cast(help.active_signature)}}, + {"activeParameter", Json{static_cast(help.active_parameter)}}}}; +} + +Json EditorDiagnostics::definition(std::string_view uri, Documents::Position position) const { + auto &s = *state_; + auto key = Documents::client_uri_key(uri); + std::shared_ptr receipt; + std::shared_ptr> facts; + { + std::lock_guard lock{s.mutex}; + const auto i = key ? s.entries.find(*key) : s.entries.end(); + if (i == s.entries.end()) + return Json{nullptr}; + receipt = i->second.receipt; + facts = i->second.occurrences; + } + if (!receipt || !facts || !s.valid(*receipt)) + return Json{nullptr}; + const auto *match = covering(*receipt, *facts, *key, position); + if (!match || !match->has_definition()) + return Json{nullptr}; + const auto &target = *match->definition_file; + const auto target_uri = target.identity.is_file_uri + ? target.identity.canonical_uri + : Documents::path_to_file_uri(target.identity.canonical_path); + return Json{Json::Object{{"uri", Json{target_uri}}, {"range", range_json(match->definition)}}}; +} +} // namespace vls::semantic diff --git a/src/semantic/Occurrences.cpp b/src/semantic/Occurrences.cpp new file mode 100644 index 0000000..10fa271 --- /dev/null +++ b/src/semantic/Occurrences.cpp @@ -0,0 +1,195 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace vls::semantic { +namespace P = Void::LanguageServer::Protocol; +using Json = P::Json; + +namespace { +constexpr std::size_t max_report = 1024 * 1024; +constexpr std::size_t max_occurrences = 256; +constexpr std::size_t max_name = 64; +constexpr std::size_t max_type = 160; +constexpr std::size_t max_signature = 300; +constexpr std::size_t max_reason = 128; +constexpr std::size_t max_path = 4095; + +bool plain(std::string_view text, std::size_t limit) { + return text.size() <= limit && + std::ranges::none_of(text, [](unsigned char c) { return c < 32 || c == 127; }); +} + +bool identifier(std::string_view name) { + if (name.empty() || name.size() > max_name) + return false; + for (std::size_t i = 0; i != name.size(); ++i) { + const char c = name[i]; + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || + (i && c >= '0' && c <= '9'))) + return false; + } + return true; +} + +const Json *member(const Json &value, std::string_view key) { + const auto *object = P::as_object(&value); + return object ? P::find_member(*object, key) : nullptr; +} + +std::optional integer(const Json *value) { + if (!value) + return {}; + if (const auto *number = std::get_if(&value->value)) + return *number; + return {}; +} + +struct RawSpan { + std::string path; + std::uint32_t line, start, end; +}; + +std::optional span(const Json *value) { + const auto *object = value ? P::as_object(value) : nullptr; + if (!object || object->size() != 4) + return {}; + const auto *path = P::as_string(P::find_member(*object, "path")); + const auto line = integer(P::find_member(*object, "line")); + const auto start = integer(P::find_member(*object, "startByte")); + const auto end = integer(P::find_member(*object, "endByte")); + constexpr auto maximum = std::numeric_limits::max(); + if (!path || !plain(*path, max_path) || path->find('\0') != path->npos || !line || !start || + !end || *line < 1 || *line > maximum || *start < 1 || *end <= *start || *end > maximum) + return {}; + return RawSpan{*path, static_cast(*line), static_cast(*start), + static_cast(*end)}; +} + +bool captured(std::span capture, const std::string &path) { + return std::ranges::any_of(capture, [&](const auto &entry) { + return entry.snapshot && entry.logical_path.native() == path; + }); +} + +// Bind a physical byte span to the captured snapshot and convert it through the +// snapshot's negotiated encoding. The sliced bytes must be exactly the declared +// name and both endpoints must fall on UTF-8 boundaries. +std::optional> +bind_span(const RawSpan &raw, std::string_view name, std::span capture) { + for (const auto &entry : capture) { + if (!entry.snapshot || entry.logical_path.native() != raw.path) + continue; + const auto &snapshot = entry.snapshot; + const std::string_view text = snapshot->text; + std::size_t line_start = 0; + for (std::uint32_t line = 1; line != raw.line; ++line) { + const auto newline = text.find('\n', line_start); + if (newline == std::string_view::npos) + return {}; + line_start = newline + 1; + } + auto line_end = text.find('\n', line_start); + if (line_end == std::string_view::npos) + line_end = text.size(); + const std::size_t width = line_end - line_start; + if (raw.start - 1 > width || raw.end - 1 > width) + return {}; + const std::size_t begin = line_start + raw.start - 1; + const std::size_t end = line_start + raw.end - 1; + if (text.substr(begin, name.size()) != name) + return {}; + if (begin && (static_cast(text[begin - 1]) & 0xC0) == 0x80) + return {}; + if (end < text.size() && (static_cast(text[end]) & 0xC0) == 0x80) + return {}; + const auto start = snapshot->offset_to_position(begin); + const auto finish = snapshot->offset_to_position(end); + if (!start || !finish || !(*start < *finish)) + return {}; + return std::pair{snapshot, Documents::Range{*start, *finish}}; + } + return {}; +} +} // namespace + +std::expected +decode_occurrences(std::string_view report, std::string_view nonce, + std::span capture) { + if (report.empty() || report.size() > max_report) + return std::unexpected{OccurrenceError::invalid_report}; + auto parsed = P::parse_json(report, 8); + if (!parsed) + return std::unexpected{OccurrenceError::invalid_report}; + const auto *root = P::as_object(&*parsed); + if (!root || root->size() != 6) + return std::unexpected{OccurrenceError::invalid_report}; + const auto schema = integer(P::find_member(*root, "schema")); + const auto *nonce_text = P::as_string(P::find_member(*root, "nonce")); + const auto complete = P::as_bool(P::find_member(*root, "complete")); + const auto partial = P::as_bool(P::find_member(*root, "partial")); + const auto *reason = P::as_string(P::find_member(*root, "reason")); + const auto *items = P::as_array(P::find_member(*root, "occurrences")); + if (!schema || *schema != 1 || !nonce_text || !complete || !partial || !reason || + !plain(*reason, max_reason) || !items || items->size() > max_occurrences) + return std::unexpected{OccurrenceError::invalid_report}; + if (*nonce_text != nonce) + return std::unexpected{OccurrenceError::wrong_nonce}; + OccurrenceReport result{{}, *complete, *partial, *reason}; + if (!*complete) + return result; + std::set> uses; + for (const auto &item : *items) { + const auto *fields = P::as_object(&item); + if (!fields || (fields->size() != 5 && fields->size() != 6)) + return std::unexpected{OccurrenceError::invalid_report}; + const auto *name = P::as_string(P::find_member(*fields, "name")); + const auto *type = P::as_string(P::find_member(*fields, "type")); + const auto *canonical = P::as_string(P::find_member(*fields, "canonicalType")); + const auto *signature = P::as_string(P::find_member(*fields, "signature")); + if (!name || !identifier(*name) || !type || !plain(*type, max_type) || type->empty() || + !canonical || !plain(*canonical, max_type) || canonical->empty() || + (signature && (!plain(*signature, max_signature) || signature->empty()))) + return std::unexpected{OccurrenceError::invalid_report}; + const auto use_span = span(P::find_member(*fields, "use")); + if (!use_span) + return std::unexpected{OccurrenceError::invalid_report}; + auto use = bind_span(*use_span, *name, capture); + if (!use) + return std::unexpected{OccurrenceError::invalid_report}; + if (!uses.emplace(use->first.get(), use->second.start.line, use->second.start.character) + .second) + return std::unexpected{OccurrenceError::invalid_report}; + Occurrence occurrence; + occurrence.name = *name; + occurrence.type = *type; + occurrence.canonical_type = *canonical; + if (signature) + occurrence.signature = *signature; + occurrence.use_file = use->first; + occurrence.use = use->second; + const auto *definition = P::find_member(*fields, "definition"); + if (definition && !std::holds_alternative(definition->value)) { + const auto definition_span = span(definition); + if (!definition_span) + return std::unexpected{OccurrenceError::invalid_report}; + if (captured(capture, definition_span->path)) { + auto bound = bind_span(*definition_span, *name, capture); + if (!bound) + return std::unexpected{OccurrenceError::invalid_report}; + occurrence.definition_file = bound->first; + occurrence.definition = bound->second; + } + } + result.occurrences.push_back(std::move(occurrence)); + } + return result; +} +} // namespace vls::semantic diff --git a/src/semantic/SourceCatalog.cpp b/src/semantic/SourceCatalog.cpp new file mode 100644 index 0000000..f90bd6d --- /dev/null +++ b/src/semantic/SourceCatalog.cpp @@ -0,0 +1,483 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace vls::semantic { +namespace fs = std::filesystem; +namespace File = Void::LanguageServer::Detail; +using Void::System::OwnedFd; +using Issue = SourceIssue; + +// Shared by old and new grant generations. Historical readers keep their own reservations. +struct SourceAccounting { + std::mutex mutex; + std::size_t handles{}, descriptors{}, bytes{}; +}; + +namespace { +auto fail(Issue issue, const fs::path &path = {}) { + return std::unexpected(SourceError{issue, path.native().size() <= 4095 ? path : fs::path{}}); +} + +struct Reservation { + std::shared_ptr account; + std::size_t descriptors{}, bytes{}; + + explicit Reservation(std::shared_ptr account) : account(std::move(account)) {} + Reservation(const Reservation &) = delete; + ~Reservation() { + std::lock_guard lock{account->mutex}; + --account->handles; + account->descriptors -= descriptors; + account->bytes -= bytes; + } + bool claim(std::size_t fds, std::size_t size) { + std::lock_guard lock{account->mutex}; + if (fds > 512 - account->descriptors || size > 192 * 1024 * 1024 - account->bytes) + return false; + account->descriptors += fds; + account->bytes += size; + descriptors += fds; + bytes += size; + return true; + } +}; + +std::shared_ptr reserve(const std::shared_ptr &account) { + std::lock_guard lock{account->mutex}; + if (account->handles >= 64) + return {}; + auto reservation = std::make_shared(account); + ++account->handles; + return reservation; +} + +bool direct_name(const fs::path &path) { + return File::valid_path(path) && path.is_absolute() && + path.native() == path.lexically_normal().native() && + (path == path.root_path() || path.has_filename()) && + std::distance(path.begin(), path.end()) <= 64; +} + +bool below(const fs::path &path, const fs::path &root) { + auto [r, p] = std::mismatch(root.begin(), root.end(), path.begin(), path.end()); + return r == root.end() && p != path.end(); +} + +struct Pin { + OwnedFd fd; + struct stat state; +}; +using Directory = std::shared_ptr; + +bool same_object(const struct stat &a, const struct stat &b) { + return a.st_dev == b.st_dev && a.st_ino == b.st_ino; +} + +OwnedFd open_directory(const fs::path &path) { + open_how how{}; + how.flags = O_PATH | O_CLOEXEC | O_DIRECTORY; + how.resolve = RESOLVE_NO_SYMLINKS | RESOLVE_NO_MAGICLINKS; + return OwnedFd{ + static_cast(::syscall(SYS_openat2, AT_FDCWD, path.c_str(), &how, sizeof how))}; +} + +std::expected pin_directory(const fs::path &path, + Reservation &reservation) { + auto fd = open_directory(path); + struct stat state{}; + if (!fd) + return fail(errno == ELOOP || errno == ENOTDIR ? Issue::unsupported_route + : Issue::unavailable, + path); + if (::fstat(fd.get(), &state) != 0) + return fail(Issue::unavailable, path); + if (!reservation.claim(1, path.native().size())) + return fail(Issue::resource_limit, path); + return std::make_shared(std::move(fd), state); +} + +bool directory_current(const fs::path &path, const Pin &pin) { + auto fd = open_directory(path); + struct stat state{}; + return fd && ::fstat(fd.get(), &state) == 0 && same_object(pin.state, state); +} + +SourceIssue from_document(const Documents::DocumentError &error) { + using K = Documents::DocumentError::Kind; + switch (error.kind) { + case K::resource_limit: + return Issue::resource_limit; + case K::stale_read: + return Issue::changed; + case K::invalid_utf8: + return Issue::invalid_text; + case K::invalid_uri: + return Issue::invalid_path; + default: + return Issue::unavailable_overlay; + } +} + +struct Leaf { + Directory parent; + fs::path name; + OwnedFd object; + struct stat state{}; +}; + +bool leaf_current(const Leaf &leaf) { + struct stat state{}; + if (::fstatat(leaf.parent->fd.get(), leaf.name.c_str(), &state, AT_SYMLINK_NOFOLLOW) != 0) + return !leaf.object && errno == ENOENT; + return leaf.object && File::same_file_state(leaf.state, state); +} +} // namespace + +struct SourceGrant { + SourceScope scope; + std::shared_ptr reservation; + Directory workspace; + std::map roots; +}; + +struct SourceEvidence { + InstalledSourceGrant grant; + std::shared_ptr reservation; + Documents::FileOverlayGeneration membership; + std::map directories; + std::vector> leaves; + std::vector observations; + std::atomic_bool expired{}; + + SourceEvidence(InstalledSourceGrant grant, std::shared_ptr reservation, + Documents::FileOverlayGeneration membership) + : grant(std::move(grant)), reservation(std::move(reservation)), + membership(std::move(membership)) {} +}; + +SourceCapture::SourceCapture(std::shared_ptr evidence) + : evidence_(std::move(evidence)) {} + +SourceCatalog::SourceCatalog(const Documents::DocumentStore &documents, + std::function before_capture_validation) + : documents_(documents), accounting_(std::make_shared()), + before_capture_validation_(std::move(before_capture_validation)) {} + +std::expected +SourceCatalog::install(const SourceScope &scope, std::span directories) { + std::lock_guard lock{installations_}; + installed_.store({}); + if (!direct_name(scope.workspace.root) || scope.workspace.session.empty() || + scope.workspace.session.size() > 4096 || scope.workspace.session.contains('\0')) + return fail(Issue::invalid_path, scope.workspace.root); + if (directories.empty() || directories.size() > 32) + return fail(Issue::resource_limit); + auto reservation = reserve(accounting_); + if (!reservation) + return fail(Issue::resource_limit); + auto workspace = pin_directory(scope.workspace.root, *reservation); + if (!workspace) + return std::unexpected(workspace.error()); + auto grant = std::make_shared(scope, std::move(reservation), *workspace, + std::map{}); + for (const auto &name : directories) { + if (!direct_name(name)) + return fail(Issue::invalid_path, name); + if (grant->roots.contains(name)) + continue; + auto pin = + name == scope.workspace.root ? workspace : pin_directory(name, *grant->reservation); + if (!pin) + return std::unexpected(pin.error()); + grant->roots.emplace(name, std::move(*pin)); + } + installed_.store(grant); + return grant; +} + +void SourceCatalog::revoke() { + std::lock_guard lock{installations_}; + installed_.store({}); +} + +namespace { +using Roots = std::map; +Roots::const_iterator owning_root(const Roots &roots, const fs::path &path) { + auto owner = roots.end(); + for (auto root = roots.begin(); root != roots.end(); ++root) + if (below(path, root->first) && + (owner == roots.end() || root->first.native().size() > owner->first.native().size())) + owner = root; + return owner; +} + +std::expected check_requests(const SourceGrant &grant, + std::span requests, + const SourceLimits &limits) { + if (requests.size() > std::min(limits.files, SourceLimits{}.files)) + return fail(Issue::resource_limit); + auto remaining = std::min(limits.name_bytes, SourceLimits{}.name_bytes); + std::set file_names; + for (const auto &[path, allow_missing, lookup_only] : requests) { + if (!direct_name(path) || !path.has_filename()) + return fail(Issue::invalid_path, path); + if (path.native().size() > remaining) + return fail(Issue::resource_limit, path); + remaining -= path.native().size(); + if (owning_root(grant.roots, path) == grant.roots.end() && + !(lookup_only && grant.roots.contains(path))) + return fail(Issue::outside_scope, path); + if (!lookup_only) + file_names.insert(path); + } + for (const auto &request : requests) + for (auto p = request.path.parent_path(); p != p.root_path(); p = p.parent_path()) + if (file_names.contains(p)) + return fail(Issue::conflicting_names, request.path); + return {}; +} + +std::expected parent_directory(SourceEvidence &evidence, + const fs::path &path, std::size_t max_fds) { + const auto root = owning_root(evidence.grant->roots, path); + auto name = root->first; + auto current = root->second; + if (!directory_current(name, *current)) + return fail(Issue::changed, name); + evidence.directories.try_emplace(name, current); + const auto relative = path.lexically_relative(name); + for (const auto &part : relative.parent_path()) { + name /= part; + if (auto i = evidence.directories.find(name); i != evidence.directories.end()) { + current = i->second; + continue; + } + OwnedFd fd{::openat(current->fd.get(), part.c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC)}; + if (!fd) + return fail(errno == ENOENT ? Issue::missing_parent : Issue::unavailable, name); + struct stat state{}; + if (::fstat(fd.get(), &state) != 0) + return fail(Issue::unavailable, name); + if (!S_ISDIR(state.st_mode)) + return fail(Issue::unsupported_route, name); + if (evidence.reservation->descriptors >= max_fds || + !evidence.reservation->claim(1, name.native().size())) + return fail(Issue::resource_limit, name); + current = std::make_shared(std::move(fd), state); + evidence.directories.emplace(name, current); + } + // A cached intermediate directory may have moved since the previous request. + if (!directory_current(name, *current)) + return fail(Issue::changed, name); + return current; +} + +std::expected bind_leaf(Directory parent, const fs::path &path, + Reservation &budget, std::size_t max_fds, + bool allow_directory = false) { + Leaf leaf{std::move(parent), path.filename(), {}}; + leaf.object = OwnedFd{ + ::openat(leaf.parent->fd.get(), leaf.name.c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC)}; + if (!leaf.object) { + if (errno == ENOENT) + return leaf; + return fail(Issue::unavailable, path); + } + if (::fstat(leaf.object.get(), &leaf.state) != 0) + return fail(Issue::unavailable, path); + if (S_ISLNK(leaf.state.st_mode)) + return fail(Issue::unsupported_route, path); + if (!S_ISREG(leaf.state.st_mode) && !(allow_directory && S_ISDIR(leaf.state.st_mode))) + return fail(Issue::not_regular, path); + if (S_ISREG(leaf.state.st_mode) && leaf.state.st_nlink != 1) + return fail(Issue::hard_link, path); + if (budget.descriptors >= max_fds || !budget.claim(1, 0)) + return fail(Issue::resource_limit, path); + return leaf; +} + +using Snapshot = std::shared_ptr; +std::expected +read_source(const Documents::DocumentStore &documents, + const Documents::BoundSourceObservation &observation, const Leaf &leaf, + const SourceRequest &request, Reservation &budget, std::size_t limit) { + const auto &overlay = observation.overlay(); + if (!overlay && !leaf.object) { + if (!request.allow_missing) + return fail(Issue::missing, request.path); + return Snapshot{}; + } + if (!overlay && leaf.state.st_size < 0) + return fail(Issue::unavailable, request.path); + const auto size = + overlay ? overlay->text.size() : static_cast(leaf.state.st_size); + if (size > limit || !budget.claim(0, size)) + return fail(Issue::resource_limit, request.path); + if (overlay) + return overlay; + std::string bytes; + bytes.reserve(size); + auto result = File::stream_regular_fd( + leaf.object, leaf.state, limit, false, [&](std::span chunk) { + bytes.append(reinterpret_cast(chunk.data()), chunk.size()); + return true; + }); + if (!result) + return fail(result.error() == File::FileError::changed ? Issue::changed + : Issue::unavailable, + request.path); + auto snapshot = documents.materialize_bound_disk(observation, std::move(bytes)); + if (!snapshot) + return fail(from_document(snapshot.error()), request.path); + return *snapshot; +} +} // namespace + +std::expected, SourceError> +SourceCatalog::capture(const SourceScope &job, const InstalledSourceGrant &grant, + const Documents::FileOverlayInventory &census, + std::span requests, SourceLimits limits) const { + if (!grant || installed_.load() != grant || job != grant->scope) + return fail(Issue::wrong_authority); + if (!directory_current(job.workspace.root, *grant->workspace)) + return fail(Issue::changed, job.workspace.root); + if (auto checked = check_requests(*grant, requests, limits); !checked) + return std::unexpected(checked.error()); + if (auto checked = documents_.validate_bound_sources(census); !checked) + return fail(from_document(checked.error())); + auto reservation = reserve(accounting_); + if (!reservation) + return fail(Issue::resource_limit); + auto evidence = + std::make_shared(grant, std::move(reservation), census.generation()); + std::shared_ptr result{new SourceCapture(evidence)}; + auto remaining = std::min(limits.total_bytes, SourceLimits{}.total_bytes); + const auto file_limit = std::min(limits.file_bytes, SourceLimits{}.file_bytes); + const auto max_fds = std::min(limits.descriptors, SourceLimits{}.descriptors); + std::map, fs::path> regular_names; + std::set open_names; + for (const auto &entry : census.entries()) + open_names.insert(entry.identity.canonical_path); + for (const auto &request : requests) { + const auto &path = request.path; + for (auto p = path.parent_path(); p != p.root_path(); p = p.parent_path()) + if (open_names.contains(p)) + return fail(Issue::conflicting_names, p); + auto observed = + documents_.observe_bound_source(census, Documents::path_to_file_uri(path), path); + if (!observed) + return fail(from_document(observed.error()), path); + if (!evidence->reservation->claim(0, path.native().size())) + return fail(Issue::resource_limit, path); + if (auto root = grant->roots.find(path); + request.lookup_only && root != grant->roots.end()) { + if (observed->overlay()) + return fail(Issue::conflicting_names, path); + evidence->directories.try_emplace(path, root->second); + evidence->observations.push_back(std::move(*observed)); + result->entries_.push_back({path, {}, SourceNode::directory}); + continue; + } + auto parent = parent_directory(*evidence, path, max_fds); + if (!parent && request.lookup_only && parent.error().issue == Issue::missing_parent) { + const auto &first_missing = parent.error().path; + auto it = open_names.lower_bound(first_missing); + if (it != open_names.end() && (*it == first_missing || below(*it, first_missing))) + return fail(Issue::missing_parent, first_missing); + auto anchor = evidence->directories.find(first_missing.parent_path()); + if (anchor == evidence->directories.end()) + return fail(Issue::changed, first_missing); + Leaf missing{anchor->second, first_missing.filename(), {}}; + evidence->leaves.emplace_back(first_missing, std::move(missing)); + evidence->observations.push_back(std::move(*observed)); + result->entries_.push_back({path, {}, SourceNode::missing}); + continue; + } + if (!parent) + return std::unexpected(parent.error()); + auto leaf = bind_leaf(*parent, path, *evidence->reservation, max_fds, request.lookup_only); + if (!leaf) + return std::unexpected(leaf.error()); + if (leaf->object && S_ISDIR(leaf->state.st_mode)) { + if (observed->overlay()) + return fail(Issue::conflicting_names, path); + evidence->directories.try_emplace( + path, std::make_shared(std::move(leaf->object), leaf->state)); + evidence->observations.push_back(std::move(*observed)); + result->entries_.push_back({path, {}, SourceNode::directory}); + continue; + } + if (leaf->object) { + auto [it, added] = + regular_names.try_emplace({leaf->state.st_dev, leaf->state.st_ino}, path); + if (!added && it->second != path) + return fail(Issue::conflicting_names, path); + } + if (installed_.load() != grant) + return fail(Issue::wrong_authority); + const auto node = + leaf->object || observed->overlay() ? SourceNode::regular : SourceNode::missing; + if (node == SourceNode::missing) { + const auto it = open_names.upper_bound(path); + if (it != open_names.end() && below(*it, path)) + return fail(Issue::missing_parent, path); + } + std::expected snapshot{Snapshot{}}; + if (!request.lookup_only) + snapshot = read_source(documents_, *observed, *leaf, request, *evidence->reservation, + std::min(remaining, file_limit)); + if (!snapshot) + return std::unexpected(snapshot.error()); + if (*snapshot) + remaining -= (*snapshot)->text.size(); + std::optional modified; + if (*snapshot) + modified = leaf->object ? leaf->state.st_mtim.tv_sec : (*snapshot)->created_at; + result->entries_.push_back({path, std::move(*snapshot), node, modified}); + evidence->leaves.emplace_back(path, std::move(*leaf)); + evidence->observations.push_back(std::move(*observed)); + } + if (before_capture_validation_) + before_capture_validation_(); + if (auto checked = validate(job, *result); !checked) + return std::unexpected(checked.error()); + return result; +} + +std::expected SourceCatalog::validate(const SourceScope &job, + const SourceCapture &capture) const { + auto &e = *capture.evidence_; + if (e.grant != installed_.load() || e.grant->scope != job) + return fail(Issue::wrong_authority); + auto expire = [&](const fs::path &path) { + e.expired = true; + return fail(Issue::changed, path); + }; + if (e.expired || !directory_current(job.workspace.root, *e.grant->workspace)) + return expire(job.workspace.root); + for (const auto &[path, dir] : e.directories) + if (!directory_current(path, *dir)) + return expire(path); + for (const auto &[path, leaf] : e.leaves) + if (!leaf_current(leaf)) + return expire(path); + if (auto current = documents_.validate_bound_sources(e.membership, e.observations); !current) + return expire({}); + if (e.grant != installed_.load()) + return fail(Issue::wrong_authority); + if (e.expired) + return fail(Issue::changed); + return {}; +} +} // namespace vls::semantic diff --git a/src/semantic/StockCompiler.cpp b/src/semantic/StockCompiler.cpp new file mode 100644 index 0000000..0e51004 --- /dev/null +++ b/src/semantic/StockCompiler.cpp @@ -0,0 +1,1075 @@ +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vls::semantic { +namespace fs = std::filesystem; +namespace P = Void::LanguageServer::Protocol; +namespace File = Void::LanguageServer::Detail; +namespace W = Void::LanguageServer::Workspace; +namespace B = Void::LanguageServer::Build; +using namespace std::chrono_literals; +namespace { +using Words = std::vector; +using Paths = std::set; +using Clock = std::chrono::steady_clock; + +void need(bool value, std::string_view message) { + if (!value) + throw std::runtime_error(std::string(message)); +} + +bool within(const fs::path &path, const fs::path &root) { + return std::mismatch(root.begin(), root.end(), path.begin(), path.end()).first == root.end(); +} +bool plain(std::string_view s) { + return !s.empty() && s.size() <= 4095 && + std::ranges::none_of(s, [](unsigned char c) { return c < 32 || c == 127; }); +} +bool named_store_path(const fs::path &path) { + const auto &s = path.native(); + return plain(s) && s.starts_with("/nix/store/") && s.size() > 44 && s[43] == '-' && + s.substr(11, 32).find_first_not_of("0123456789abcdfghijklmnpqrsvwxyz") == + std::string::npos && + path.lexically_normal().native() == s; +} +void immutable(const fs::path &path) { + need(named_store_path(path), "toolchain path is outside the selected immutable store"); + struct stat state{}; + need(::stat(path.c_str(), &state) == 0 && state.st_uid == 0 && !(state.st_mode & 0222), + "toolchain input is missing or writable"); + std::error_code error; + auto actual = fs::canonical(path, error); + need(!error && named_store_path(actual), "toolchain input resolves outside the store"); +} +std::string read_file(const fs::path &path, std::size_t limit, bool executable = false) { + std::string bytes; + auto read = File::read_regular(path, limit, executable, [&](std::span chunk) { + bytes.append(reinterpret_cast(chunk.data()), chunk.size()); + return true; + }); + need(read.has_value(), "could not read a bounded regular input"); + return bytes; +} +const P::Json *field(const P::Json &v, std::string_view name) { + auto o = P::as_object(&v); + return o ? P::find_member(*o, name) : nullptr; +} +std::string string_field(const P::Json &v, std::string_view name) { + auto s = P::as_string(field(v, name)); + need(s && plain(*s), "invalid compiler profile field"); + return *s; +} +Words strings(const P::Json &v, std::string_view name, std::size_t limit) { + auto items = P::as_array(field(v, name)); + need(items && items->size() <= limit, "invalid compiler profile list"); + Words result; + for (auto &item : *items) { + auto s = P::as_string(&item); + need(s && plain(*s), "invalid compiler profile word"); + result.push_back(*s); + } + return result; +} +bool mounted(const GccProfile &p, const fs::path &path) { + return std::ranges::any_of(p.mounts, [&](const auto &m) { return within(path, m); }); +} +fs::path tool(const P::Json &root, std::string_view name) { + auto item = field(root, name); + need(item, "missing compiler profile tool"); + fs::path path = string_field(*item, "path"); + immutable(path); + auto id = W::inspect_tool_identity(path); + need(id && id->canonical_path == path && id->content_hash_hex == string_field(*item, "sha256"), + "toolchain executable has changed since profile preparation"); + return path; +} +// A launcher-selected local observer. Unlike the toolchain it is a development +// artifact, so its exact bytes are re-verified for every job instead of relying +// on an immutable store path. +fs::path observer_tool(const P::Json &root, std::string &identity) { + const auto *item = field(root, "observer"); + if (!item) + return {}; + const auto *fields = P::as_object(item); + need(fields && fields->size() == 2, "invalid observer profile entry"); + fs::path path = string_field(*item, "path"); + identity = string_field(*item, "sha256"); + need(path.is_absolute() && plain(path.native()) && fs::is_regular_file(path), + "observer artifact is unavailable"); + need(identity.size() == 64 && + identity.find_first_not_of("0123456789abcdef") == std::string::npos, + "invalid observer digest"); + return path; +} +Words sandbox(const GccProfile &p, const fs::path &cwd, std::uint32_t memory_mib, + const fs::path &observer = fs::path{}) { + const auto address_space = std::min(memory_mib, 1536u) * (1024ull * 1024); + Words args{"--as=" + std::to_string(address_space), + "--cpu=25", + "--fsize=67108864", + "--nofile=256", + "--core=0", + "--", + p.bubblewrap.native(), + "--unshare-all", + "--die-with-parent", + "--new-session", + "--clearenv", + "--setenv", + "LC_ALL", + "C", + "--setenv", + "TZ", + "UTC0", + "--setenv", + "TZDIR", + p.frontend.parent_path().native(), + "--dev", + "/dev", + "--proc", + "/proc", + "--size", + "67108864", + "--tmpfs", + "/tmp"}; + auto key = "NIX_CFLAGS_COMPILE_" + p.target; + std::ranges::replace(key, '-', '_'); + args.insert(args.end(), {"--setenv", key, p.flags}); + for (auto &m : p.mounts) + args.insert(args.end(), {"--ro-bind", m.native(), m.native()}); + if (!observer.empty()) { + args.insert(args.end(), + {"--dir", "/vls-observer", "--ro-bind", (observer / "occurrences.so").native(), + "/vls-observer/occurrences.so", "--ro-bind", (observer / "inputs").native(), + "/vls-observer/inputs", "--bind", (observer / "report").native(), + "/vls-observer/report"}); + } + args.insert(args.end(), {"--dir", cwd.native(), "--chdir", cwd.native()}); + return args; +} + +Void::Process::CommunicateResult execute(const GccProfile &p, Words args, std::stop_token stop, + Clock::time_point deadline, std::size_t output) { + need(!stop.stop_requested(), "compiler job cancelled"); + auto time = std::chrono::duration_cast(deadline - Clock::now()); + need(time > 0ms, "compiler job exceeded its deadline"); + Void::Process::SpawnOptions options; + options.executable = p.prlimit; + options.arguments = std::move(args); + options.environment.mode = Void::Process::EnvMode::explicit_only; + options.environment.set_vars = {{"LC_ALL", "C"}}; + options.working_directory = "/"; + options.search_path = false; + options.kill_grace = 100ms; + auto child = Void::Process::spawn(options); + need(bool(child), "could not start isolated compiler"); + auto received = Void::Process::communicate_blocking(*child, {}, + {.max_stdout_bytes = output, + .max_stderr_bytes = 4 * 1024 * 1024, + .max_line_bytes = 4 * 1024 * 1024}, + time, stop); + need(bool(received), "compiler process communication failed"); + need(!received->cancelled && !stop.stop_requested(), "compiler job cancelled"); + need(!received->timed_out && !received->overflowed && !received->stdout_truncated && + !received->stderr_truncated && received->status.exited, + "incomplete compiler process output"); + return std::move(*received); +} + +// GCC's -### prints an argv quoted for the shell. Decode it as data and pass the +// resulting strings directly to exec. No shell evaluation or environment expansion occurs. +Words printed_argv(std::string_view line) { + Words words; + std::string word; + char quote{}; + bool started{}; + for (std::size_t i = 0; i < line.size(); ++i) { + char c = line[i]; + if (!quote && (c == ' ' || c == '\t')) { + if (started) { + words.push_back(std::move(word)); + word.clear(); + started = false; + } + continue; + } + started = true; + if (quote && c == quote) { + quote = 0; + continue; + } + if (!quote && (c == '"' || c == '\'')) { + quote = c; + continue; + } + if (c == '\\' && quote != '\'') { + need(i + 1 < line.size(), "truncated GCC quoting"); + if (!quote || std::string_view{"\"\\$`"}.contains(line[i + 1])) + c = line[++i]; + } + word += c; + } + need(!quote, "unterminated GCC quoting"); + if (started) + words.push_back(std::move(word)); + return words; +} +Words frontend_args(const GccProfile &p, const B::BuildContext &row, std::uint32_t memory_mib, + std::stop_token stop, Clock::time_point end) { + const auto &semantic = *row.semantic_arguments; + need(semantic.size() > 1 && semantic.size() <= 1024 && semantic.front() == p.driver, + "selected compiler command does not match the stock profile"); + auto args = sandbox(p, *row.working_directory, memory_mib); + args.insert(args.end(), {"--", p.driver.native(), "-###"}); + args.insert(args.end(), semantic.begin() + 1, semantic.end()); + args.insert(args.end(), + {"-fsyntax-only", "-fdiagnostics-format=sarif-stderr", "-frandom-seed=vls"}); + auto discovery = execute(p, std::move(args), stop, end, 4096); + need(discovery.status.code == 0 && discovery.out.empty(), + "GCC could not resolve the selected command"); + Words invocation; + std::string_view log = discovery.err; + while (!log.empty()) { + auto n = log.find('\n'); + auto line = log.substr(0, n); + log.remove_prefix(n == log.npos ? log.size() : n + 1); + auto first = line.find_first_not_of(" \t"); + if (first == line.npos) + continue; + line.remove_prefix(first); + if (!line.starts_with('/') && !line.starts_with("\"/")) + continue; + auto words = printed_argv(line); + need(invocation.empty() && !words.empty() && words.front() == p.frontend, + "driver dry run did not select exactly the approved C++ frontend"); + invocation = std::move(words); + } + need(!invocation.empty() && + std::ranges::contains(invocation, std::string_view{"-fsyntax-only"}) && + std::ranges::contains(invocation, + std::string_view{"-fdiagnostics-format=sarif-stderr"}) && + std::ranges::count(invocation, row.key.owning_tu.native()) == 1, + "could not establish the owning TU in the GCC frontend command"); + return invocation; +} + +int hex(char c) { + if (c >= '0' && c <= '9') + return c - '0'; + return c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1; +} +std::string path_word(std::string_view args) { + need(args.starts_with('"'), "unavailable filename in GCC lookup observation"); + args.remove_prefix(1); + std::string result; + while (!args.empty() && args.front() != '"') { + need(args.size() >= 4 && args.starts_with("\\x") && hex(args[2]) >= 0 && hex(args[3]) >= 0, + "unknown encoding in GCC lookup observation"); + result += static_cast((hex(args[2]) << 4) | hex(args[3])); + args.remove_prefix(4); + need(result.size() <= 4095, "oversized GCC lookup"); + } + need(args.size() >= 2 && args.front() == '"' && (args[1] == ',' || args[1] == ')') && + !result.contains('\0'), + "truncated GCC lookup observation"); + return result; +} +struct FileAudit { + Paths workspace, system_files; +}; + +FileAudit audit(const GccProfile &p, std::string_view bytes, int status, const fs::path &root, + const fs::path &cwd, const fs::path &tu) { + FileAudit out; + bool executed{}, ended{}, opened_tu{}; + std::size_t count{}; + while (!bytes.empty()) { + const auto n = bytes.find('\n'); + need(n != bytes.npos && n <= 512 * 1024 && ++count <= 200000, + "incomplete GCC lookup observation"); + auto line = bytes.substr(0, n); + bytes.remove_prefix(n + 1); + if (line == "+++ exited with " + std::to_string(status) + " +++") { + need(bytes.empty(), "extra compiler lookup records"); + ended = true; + break; + } + const auto bracket = line.find('('), result = line.rfind(" = "); + need(bracket != line.npos && result != line.npos, "unexpected GCC lookup observation"); + const auto call = line.substr(0, bracket); + auto args = line.substr(bracket + 1, result - bracket - 1); + const bool success = !line.substr(result + 3).starts_with('-'); + if (call == "execve") { + need(!executed && success && path_word(args) == p.frontend, + "unexpected compiler execution"); + executed = true; + continue; + } + need(executed, "lookup before compiler execution"); + if (call == "getcwd") + continue; + if (call == "openat" || call == "newfstatat" || call == "statx" || call == "faccessat" || + call == "faccessat2" || call == "readlinkat") { + auto comma = args.find(", "); + need(comma != args.npos, "invalid compiler directory lookup"); + const bool relative_base = args.substr(0, comma) == "AT_FDCWD"; + args.remove_prefix(comma + 2); + if (args.starts_with("\"\",") && args.contains("AT_EMPTY_PATH")) + continue; + need(relative_base || args.starts_with("\"\\x2f"), + "unsupported compiler directory descriptor"); + } else { + need(call == "open" || call == "stat" || call == "lstat" || call == "access" || + call == "readlink", + "unsupported filesystem operation in stock compiler"); + } + fs::path raw = path_word(args); + need(!raw.empty(), "empty compiler lookup"); + auto absolute = raw.is_absolute() ? raw : cwd / raw; + fs::path path = absolute.lexically_normal(); + if (path != path.root_path() && !path.has_filename()) + path = path.parent_path(); + const bool file_open = call == "openat" || call == "open"; + if (mounted(p, path)) { + if (opened_tu && file_open && success) + out.system_files.insert(path); + } else if (within(path, root)) { + need(std::ranges::find(absolute, fs::path{".."}) == absolute.end(), + "source lookup needs parent-component provenance"); + out.workspace.insert(path); + if (path == tu && file_open && success) + opened_tu = true; + } else if (path == "/dev/null" || path == "/dev" || path == "/nix" || + path == "/nix/store" || + (!opened_tu && (path == "/etc/localtime" || path == "/etc/ld-nix.so.preload")) || + within(root, path) || + std::ranges::any_of(p.mounts, [&](auto &m) { return within(m, path); })) { + // Only directory ancestry and the fixed tool runtime are provided outside the inputs. + need(!file_open || path == "/dev/null" || + (!opened_tu && path.native().starts_with("/etc/")), + "unexpected read outside compiler roots"); + } else if (p.observes() && within(path, fs::path{"/vls-observer"})) { + // The launcher-selected observer has exactly three private runtime files. + need(path == "/vls-observer" || path == "/vls-observer/occurrences.so" || + path == "/vls-observer/inputs" || path == "/vls-observer/report", + "unexpected observer runtime lookup"); + } else + throw std::runtime_error("compiler lookup outside the approved input roots: " + + path.native().substr(0, 200)); + need(out.workspace.size() <= 1024 && out.system_files.size() <= 4096, + "too many GCC lookup inputs"); + } + need(executed && ended && opened_tu, "compiler did not finish a witnessed translation unit"); + return out; +} + +bool permitted_source(const fs::path &root, const fs::path &path) { + for (const auto &part : path.lexically_relative(root)) { + auto s = part.native(); + if (s.starts_with('.') || s == "keys" || s == "credentials" || s == "WG.conf") + return false; + } + const auto ext = path.extension().native(); + return ext.empty() || + std::ranges::contains(std::array{".c", ".cc", ".cpp", ".cxx", ".C", + ".h", ".hh", ".hpp", ".hxx", + ".inc", ".inl", ".ipp", ".tcc", + ".tpp", ".def", ".cppm", ".ixx"}, + ext); +} +bool sane_lookup(const fs::path &root, const fs::path &path) { + if (path == root) + return true; + for (const auto &part : path.lexically_relative(root)) { + auto s = part.native(); + if (s.starts_with('.') || s == "keys" || s == "credentials" || s == "WG.conf") + return false; + } + return true; +} + +using Capture = std::shared_ptr; +Capture take(const SourceCatalog &catalog, const SourceScope &scope, + const InstalledSourceGrant &grant, const Documents::FileOverlayInventory &census, + std::span requests) { + auto captured = catalog.capture(scope, grant, census, requests); + if (!captured) + throw std::runtime_error("source capture unavailable (" + + std::to_string(static_cast(captured.error().issue)) + + "): " + captured.error().path.native().substr(0, 200)); + return *captured; +} +struct View { + Capture files; + Paths directories; +}; +View assemble(const SourceCatalog &catalog, const SourceScope &scope, + const InstalledSourceGrant &grant, const Documents::FileOverlayInventory &census, + const Paths &names) { + std::vector requests; + requests.reserve(names.size()); + for (const auto &path : names) { + need(sane_lookup(scope.workspace.root, path), + "compiler requested an unapproved source name"); + requests.push_back({path, true, true}); + } + auto shapes = take(catalog, scope, grant, census, requests); + Paths directories; + for (std::size_t i = 0; i < requests.size(); ++i) { + const auto node = shapes->entries()[i].node; + if (node == SourceNode::regular) { + need(permitted_source(scope.workspace.root, requests[i].path), + "unsupported compiler input type"); + requests[i].lookup_only = false; + requests[i].allow_missing = false; + } else if (node == SourceNode::directory) + directories.insert(requests[i].path); + } + auto files = take(catalog, scope, grant, census, requests); + need(bool(catalog.validate(scope, *shapes)), "source namespace changed during acquisition"); + for (std::size_t i = 0; i < requests.size(); ++i) + need(shapes->entries()[i].node == files->entries()[i].node, + "source kind changed during acquisition"); + return {std::move(files), std::move(directories)}; +} + +// Withhold physical locations if a preprocessing directive can change a presumed filename/line. +// Comments and literals may make the check conservative. Splicing precedes directive recognition. +bool physical_lines(std::string_view bytes) { + // Only these trigraphs can introduce a directive or a line splice. + if (bytes.contains('\0') || + bytes.contains("?" + "?/") || + bytes.contains("?" + "?=")) + return false; + if (bytes.starts_with("\xef\xbb\xbf")) + bytes.remove_prefix(3); + std::string text; + text.reserve(bytes.size()); + for (std::size_t i = 0; i < bytes.size(); ++i) { + if (bytes[i] == '\\') { + auto j = i + 1; + while (j < bytes.size() && + (bytes[j] == ' ' || bytes[j] == '\t' || bytes[j] == '\v' || bytes[j] == '\f')) + ++j; + if (j < bytes.size() && (bytes[j] == '\n' || bytes[j] == '\r')) { + if (bytes[j] == '\r' && j + 1 < bytes.size() && bytes[j + 1] == '\n') + ++j; + i = j; + continue; + } + } + text += bytes[i]; + } + // A directive can start after whitespace or the end of a block comment. Treat + // every */ as a possible comment end, including ones inside raw strings. That + // can withhold a location, but cannot hide a real directive. Ordinary references + // such as "// LWG issue #615" never start a preprocessing directive. + bool possible_directive = true; + for (std::size_t pos = 0; pos < text.size(); ++pos) { + unsigned char c = text[pos]; + if (c == '\n' || c == '\r') { + possible_directive = true; + continue; + } + if (c == '*' && pos + 1 < text.size() && text[pos + 1] == '/') { + possible_directive = true; + ++pos; + continue; + } + if (c == ' ' || c == '\t' || c == '\v' || c == '\f' || c >= 128) + continue; + const bool marker = c == '#' || (c == '%' && pos + 1 < text.size() && text[pos + 1] == ':'); + const bool candidate = marker && possible_directive; + possible_directive = false; + if (!candidate) + continue; + if (c == '%') + ++pos; + std::string_view tail{text.data() + pos + 1, text.size() - pos - 1}; + for (;;) { + auto n = tail.find_first_not_of(" \r\n\t\f\v"); + if (n == tail.npos) + break; + tail.remove_prefix(n); + if (tail.starts_with("/*")) { + auto end = tail.find("*/", 2); + if (end == tail.npos) + return false; + tail.remove_prefix(end + 2); + continue; + } + unsigned char c = tail.front(); + if (tail.starts_with("line") || (c >= '0' && c <= '9') || c == '\\' || c >= 128) + return false; + break; + } + } + return true; +} + +void stage(Words &args, const View &view, const fs::path &work) { + for (auto &dir : view.directories) + args.insert(args.end(), {"--dir", dir.native()}); + std::size_t i{}; + for (auto &entry : view.files->entries()) + if (entry.snapshot) { + auto copy = work / ("input-" + std::to_string(i++)); + std::ofstream stream(copy, std::ios::binary | std::ios::trunc); + stream.write(entry.snapshot->text.data(), + static_cast(entry.snapshot->text.size())); + stream.close(); + need(stream.good(), "could not stage compiler source"); + need(entry.modified_at.has_value(), "source modification time is unavailable"); + const auto stamp = std::chrono::system_clock::from_time_t(*entry.modified_at); + fs::last_write_time(copy, fs::file_time_type::clock::from_sys(stamp)); + args.insert(args.end(), {"--ro-bind", copy.native(), entry.logical_path.native()}); + } +} + +std::string observer_nonce() { + std::array bytes{}; + std::size_t used = 0; + while (used != bytes.size()) { + const auto count = ::getrandom(bytes.data() + used, bytes.size() - used, 0); + need(count > 0, "could not acquire an observer nonce"); + used += static_cast(count); + } + constexpr char digits[] = "0123456789abcdef"; + std::string text; + for (const auto byte : bytes) { + text += digits[byte >> 4]; + text += digits[byte & 0xf]; + } + return text; +} + +// Stage the launcher-selected observer from verified bytes. A changed artifact +// withholds occurrence facts; it never fails the diagnostics job. +std::string stage_observer(const GccProfile &p, const SourceCapture &capture, const fs::path &tu, + const fs::path &work) { + const auto directory = work / "observer"; + fs::create_directory(directory); + std::error_code ignored; + fs::remove(directory / "occurrences.so", ignored); + const auto bytes = read_file(p.observer, 16 * 1024 * 1024, true); + need(Documents::compute_content_hash(bytes).sha256_hex == p.observer_identity, + "observer artifact changed since profile preparation"); + { + std::ofstream out(directory / "occurrences.so", std::ios::binary | std::ios::trunc); + out.write(bytes.data(), static_cast(bytes.size())); + out.close(); + need(out.good(), "could not stage the observer"); + } + fs::permissions(directory / "occurrences.so", fs::perms::owner_read); + const auto nonce = observer_nonce(); + std::string inputs{"VLS-OCCURRENCES-1\n" + nonce + "\n" + tu.native() + "\n"}; + for (const auto &entry : capture.entries()) + if (entry.snapshot) + inputs += entry.logical_path.native() + "\n"; + { + std::ofstream out(directory / "inputs", std::ios::binary | std::ios::trunc); + out << inputs; + out.close(); + need(out.good(), "could not stage observer inputs"); + } + std::ofstream(directory / "report", std::ios::binary | std::ios::trunc).close(); + return nonce; +} + +} // namespace + +std::expected, std::string> +GccProfile::load(const fs::path &file) { + try { + need(file.is_absolute(), "compiler profile must be an explicit absolute file"); + const auto raw = read_file(file, 128 * 1024); + auto json = P::parse_json(raw, 8); + need(bool(json), "invalid compiler profile JSON"); + const auto *schema = field(*json, "schema"); + need(schema && std::get_if(&schema->value) && + std::get(schema->value) == 1 && + string_field(*json, "version") == "16.2.0", + "unsupported GCC profile version"); + auto p = std::shared_ptr{new GccProfile}; + p->driver = tool(*json, "driver"); + p->frontend = tool(*json, "frontend"); + p->bubblewrap = tool(*json, "bubblewrap"); + p->strace = tool(*json, "strace"); + p->prlimit = tool(*json, "prlimit"); + p->target = string_field(*json, "target"); + need(p->target.size() <= 128 && + p->target.find_first_not_of( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") == + p->target.npos, + "invalid GCC target"); + for (auto &dir : strings(*json, "mounts", 160)) { + immutable(dir); + need(fs::is_directory(dir), "runtime mount is not a directory"); + p->mounts.emplace_back(dir); + } + need(mounted(*p, p->driver) && mounted(*p, p->frontend) && mounted(*p, p->strace), + "incomplete GCC runtime"); + const auto flags = strings(*json, "toolchainFlags", 256); + for (std::size_t i = 0; i < flags.size(); ++i) { + auto &s = flags[i]; + if (s.starts_with("-frandom-seed=")) { + need(s.find_first_not_of( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._=") == + s.npos, + "invalid toolchain seed"); + } else { + need((s == "-isystem" || s == "-idirafter" || s == "-I") && i + 1 < flags.size(), + "unsupported toolchain flag"); + const auto &dir = flags[++i]; + immutable(dir); + need(mounted(*p, dir) && + dir.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY" + "Z0123456789/+-._=") == dir.npos, + "unverified toolchain include root"); + } + } + for (auto &s : flags) { + if (!p->flags.empty()) + p->flags += ' '; + p->flags += s; + } + p->observer = observer_tool(*json, p->observer_identity); + p->identity = Documents::compute_content_hash(raw).display_digest(); + return p; + } catch (const std::exception &e) { + return std::unexpected(e.what()); + } +} + +std::expected +analyze_with_gcc(const GccProfile &p, const SemanticContextLease &lease, + const Documents::DocumentStore &documents, const SourceCatalog &catalog, + const InstalledSourceGrant &grant, std::uint64_t sequence, + std::span previous_lookups, std::stop_token stop) { + try { + const auto &selection = lease.selection(); + const auto *row = selection->selected; + need(row && row->working_directory && row->semantic_arguments && + row->source_language == "c++", + "selected TU does not have a checked C++ command"); + const SourceScope scope{selection->generation->identity().workspace, + lease.configuration_generation(), + lease.driver().tool.trust_generation}; + const auto &root = scope.workspace.root, &tu = row->key.owning_tu, + &cwd = *row->working_directory; + need(within(tu, root) && within(cwd, root), + "stock worker needs an admitted translation unit and working directory"); + auto census = documents.file_overlay_inventory(); + need(bool(census), "the editor source census is unavailable"); + for (const auto &open : census->entries()) + need(!mounted(p, open.identity.canonical_path), + "an open editor file overrides the immutable toolchain"); + const auto deadline = Clock::now() + 60s; + auto invocation = frontend_args(p, *row, lease.worker_memory_limit_mib(), stop, deadline); + const auto source_position = std::ranges::find(invocation, tu.native()); + need(source_position != invocation.end(), "owning TU is missing from the compiler command"); + Void::FileSystem::TempDir work{"vls-stock-gcc-"}; + Paths names{tu, cwd}; + names.insert(previous_lookups.begin(), previous_lookups.end()); + for (std::size_t i = 1; i + 1 < invocation.size(); ++i) + if (invocation[i] == "-I" || invocation[i] == "-isystem" || + invocation[i] == "-iquote" || invocation[i] == "-idirafter") { + fs::path dir = invocation[i + 1]; + if (within(dir, root)) + names.insert(dir); + } + for (std::size_t round = 1; round <= 48; ++round) { + need(!stop.stop_requested(), "compiler job cancelled"); + auto view = assemble(catalog, scope, grant, *census, names); + std::string nonce, occurrence_detail; + bool observed_facts = false; + if (p.observes()) { + try { + nonce = stage_observer(p, *view.files, tu, work.path()); + observed_facts = true; + } catch (const std::exception &error) { + occurrence_detail = error.what(); + observed_facts = false; + } + } + auto args = sandbox(p, cwd, lease.worker_memory_limit_mib(), + observed_facts ? work.path() / "observer" : fs::path{}); + stage(args, view, work.path()); + args.insert(args.end(), + {"--", p.strace.native(), "-q", "-s", "4096", "-xx", "-e", + "trace=%file,getdents,getdents64,clone,clone3,fork,vfork,fchdir", "-e", + "signal=none", "-o", "/proc/self/fd/1", "--"}); + args.insert(args.end(), invocation.begin(), source_position); + if (observed_facts) + args.insert(args.end(), "-fplugin=/vls-observer/occurrences.so"); + args.insert(args.end(), source_position, invocation.end()); + auto observed = execute(p, std::move(args), stop, deadline, 64 * 1024 * 1024); + need(observed.status.code == 0 || observed.status.code == 1, "stock compiler failed"); + auto lookups = audit(p, observed.out, observed.status.code, root, cwd, tu); + need(bool(catalog.validate(scope, *view.files)), "compiler sources changed"); + const auto previous = names.size(); + names.insert(lookups.workspace.begin(), lookups.workspace.end()); + if (names.size() != previous) + continue; + std::shared_ptr owner; + DiagnosticJob job; + B::AnalysisInputs inputs; + inputs.dependencies.emplace(); + std::optional unproven_origin; + for (auto &entry : view.files->entries()) + if (entry.snapshot) { + if (entry.logical_path == tu) + owner = entry.snapshot; + else + inputs.dependencies->push_back({B::DependencyKind::include, + entry.logical_path.native(), + entry.logical_path, entry.snapshot}); + job.artifacts.push_back({{entry.logical_path.native(), {}}, entry.snapshot}); + if (!unproven_origin && !physical_lines(entry.snapshot->text)) + unproven_origin = entry.logical_path; + } + need(owner && owner->version, "editor TU is not a synchronized open document"); + std::size_t proof_budget = 32 * 1024 * 1024; + for (auto &file : lookups.system_files) { + if (unproven_origin) + break; + try { + std::error_code ec; + auto real = fs::canonical(file, ec); + need(!ec && mounted(p, real), "unverified system header origin"); + auto data = + read_file(real, std::min(proof_budget, 4 * 1024 * 1024)); + proof_budget -= data.size(); + if (!physical_lines(data)) + unproven_origin = file; + } catch (const std::exception &) { + unproven_origin = file; + } + } + inputs.document = inputs.translation_unit = owner; + inputs.configuration_generation = scope.configuration; + inputs.trust_generation = scope.trust; + inputs.lookup_epoch = sequence; + inputs.backend = B::BackendIdentity{"stock GCC", "16.2.0", p.identity}; + auto revision = B::AnalysisRevision::capture(selection, inputs); + need(revision && (*revision)->readiness(B::Operation::diagnostics).level != + B::ReadinessLevel::unavailable, + "diagnostic context is unavailable"); + job.owner = owner; + job.inputs_complete = true; + job.invocation_id = std::to_string(sequence); + job.input_view_id = p.identity + "/" + job.invocation_id; + if (!unproven_origin) + job.physical_origin = [](const LocationRequest &) { + return std::optional{CoordinatePolicy{}}; + }; + auto batch = decode_gcc_diagnostics(job, {job.invocation_id, job.input_view_id, + observed.status.code, true, observed.err}); + need(bool(batch), "stock GCC diagnostic report could not be verified"); + need(!stop.stop_requested() && bool(catalog.validate(scope, *view.files)), + "compiler inputs were superseded"); + std::optional occurrences; + if (observed_facts) { + try { + const auto report = read_file(work.path() / "observer/report", 1024 * 1024); + if (auto decoded = decode_occurrences(report, nonce, view.files->entries())) + occurrences = std::move(*decoded); + else + occurrence_detail = "the observer report could not be verified"; + } catch (const std::exception &) { + occurrence_detail = "the observer report is unavailable"; + } + } + return StockAnalysis{std::move(*batch), + std::move(view.files), + *revision, + std::move(occurrences), + std::move(occurrence_detail), + {names.begin(), names.end()}, + round, + std::move(unproven_origin)}; + } + throw std::runtime_error("compiler source discovery exceeded its pass limit"); + } catch (const std::exception &e) { + return std::unexpected(e.what()); + } +} +std::expected +scan_modules_with_gcc(const GccProfile &p, const SemanticContextLease &lease, + const Documents::DocumentStore &documents, const SourceCatalog &catalog, + const InstalledSourceGrant &grant, std::span previous_lookups, + std::stop_token stop) { + try { + const auto &selection = lease.selection(); + const auto *row = selection->selected; + need(row && row->working_directory && row->semantic_arguments && + row->source_language == "c++", + "selected TU does not have a checked C++ command"); + const SourceScope scope{selection->generation->identity().workspace, + lease.configuration_generation(), + lease.driver().tool.trust_generation}; + const auto &root = scope.workspace.root, &tu = row->key.owning_tu, + &cwd = *row->working_directory; + need(within(tu, root) && within(cwd, root), + "module scan needs an admitted translation unit and working directory"); + auto census = documents.file_overlay_inventory(); + need(bool(census), "the editor source census is unavailable"); + const auto deadline = Clock::now() + 60s; + Void::FileSystem::TempDir work{"vls-stock-scan-"}; + const auto scan_directory = work.path() / "scan"; + fs::create_directory(scan_directory); + const auto dependency = scan_directory / "deps.json"; + Paths names{tu, cwd}; + names.insert(previous_lookups.begin(), previous_lookups.end()); + { + const auto &arguments = *row->semantic_arguments; + for (std::size_t i = 1; i + 1 < arguments.size(); ++i) + if (arguments[i] == "-I" || arguments[i] == "-isystem" || + arguments[i] == "-iquote" || arguments[i] == "-idirafter") { + fs::path directory = arguments[i + 1]; + if (within(directory, root)) + names.insert(directory); + } + } + for (std::size_t round = 1; round <= 48; ++round) { + need(!stop.stop_requested(), "module scan cancelled"); + auto view = assemble(catalog, scope, grant, *census, names); + auto invocation = + modules::build_scan_invocation(*row, {cwd, "unit.o"}, "/vls-scan/deps.json"); + need(bool(invocation), "could not derive the P1689 scan command"); + auto args = sandbox(p, cwd, lease.worker_memory_limit_mib()); + stage(args, view, work.path()); + args.insert(args.end(), {"--bind", scan_directory.native(), "/vls-scan"}); + args.insert(args.end(), {"--", invocation->arguments.front()}); + args.insert(args.end(), invocation->arguments.begin() + 1, invocation->arguments.end()); + auto observed = execute(p, std::move(args), stop, deadline, 4 * 1024 * 1024); + need(!stop.stop_requested(), "module scan cancelled"); + need(bool(catalog.validate(scope, *view.files)), "compiler sources changed"); + if (!fs::is_regular_file(dependency)) + return std::unexpected("the module scanner wrote no dependency file: " + + observed.err.substr(0, 400)); + auto bytes = read_file(dependency, modules::max_scan_bytes); + auto rule = modules::decode_scan(bytes, {cwd, "unit.o"}); + need(bool(rule), "module scan rule could not be verified"); + StockScan result; + for (const auto &module : rule->provides()) + result.provides.push_back(module.logical_name); + for (const auto &module : rule->requirements()) + result.imports.push_back(module.logical_name); + result.complete = observed.status.code == 0; + return result; + } + return std::unexpected("module scan exceeded its pass limit"); + } catch (const std::exception &error) { + return std::unexpected(error.what()); + } +} + +namespace { +std::string trim(std::string text) { + const auto first = text.find_first_not_of(" \t\r\n"); + if (first == std::string::npos) + return {}; + const auto last = text.find_last_not_of(" \t\r\n"); + return text.substr(first, last - first + 1); +} + +std::pair capture(const Words &argv, std::size_t limit = 4 * 1024 * 1024) { + Void::Process::SpawnOptions options; + options.executable = argv.front(); + options.arguments.assign(argv.begin() + 1, argv.end()); + options.search_path = argv.front().find('/') == std::string::npos; + auto child = Void::Process::spawn(options); + if (!child) + return {-1, "could not run a compiler tool"}; + auto received = Void::Process::communicate_blocking( + *child, {}, + {.max_stdout_bytes = limit, .max_stderr_bytes = limit, .max_line_bytes = limit}, + std::chrono::milliseconds{30000}, {}); + if (!received) + return {-1, "compiler tool communication failed"}; + return {received->status.exited ? received->status.code : -1, + received->err + received->out}; +} + +fs::path locate(std::string_view name) { + const char *path = std::getenv("PATH"); + need(path, "PATH is unavailable"); + std::string_view rest{path}; + while (!rest.empty()) { + const auto separator = rest.find(':'); + const fs::path directory{rest.substr(0, separator)}; + rest = separator == std::string_view::npos ? std::string_view{} + : rest.substr(separator + 1); + const auto candidate = directory / name; + std::error_code error; + if (fs::is_regular_file(candidate, error) && ::access(candidate.c_str(), X_OK) == 0) + return fs::canonical(candidate); + } + throw std::runtime_error(std::string{name} + " is not available on PATH"); +} + +fs::path store_package(const fs::path &path) { + std::vector parts{path.begin(), path.end()}; + need(parts.size() >= 4 && parts[0] == "/" && parts[1] == "nix" && parts[2] == "store", + "expected an immutable Nix store input: " + path.native().substr(0, 200)); + const fs::path package = parts[0] / parts[1] / parts[2] / parts[3]; + need(named_store_path(package), "expected an immutable Nix store input: " + package.native().substr(0, 200)); + return package; +} +} // namespace + +std::expected, std::string> +GccProfile::prepare(const fs::path &driver_path) { + try { + const fs::path driver = + driver_path.has_parent_path() ? fs::canonical(driver_path) : locate(driver_path.native()); + auto [version_status, version_text] = capture({driver.native(), "-dumpfullversion"}); + need(version_status == 0 && trim(version_text) == "16.2.0", + "the in-process profile requires GCC 16.2.0"); + auto [target_status, target_text] = capture({driver.native(), "-dumpmachine"}); + need(target_status == 0, "could not query the GCC target"); + const auto target = trim(target_text); + need(!target.empty() && target.size() <= 128 && + target.find_first_not_of( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") == + std::string::npos, + "invalid GCC target"); + auto profile = std::shared_ptr{new GccProfile}; + profile->driver = driver; + profile->bubblewrap = locate("bwrap"); + profile->strace = locate("strace"); + profile->prlimit = locate("prlimit"); + const Words probe{driver.native(), + "-###", + "-fsyntax-only", + "-fdiagnostics-format=sarif-stderr", + "-frandom-seed=vls-probe", + "-std=c++26", + "-freflection", + "/vls-check/sample.cpp"}; + auto [probe_status, probe_text] = capture(probe); + static_cast(probe_status); + Words reference; + std::string_view log = probe_text; + while (!log.empty()) { + const auto end = log.find('\n'); + auto line = log.substr(0, end); + log.remove_prefix(end == std::string_view::npos ? log.size() : end + 1); + const auto first = line.find_first_not_of(" \t"); + if (first == std::string_view::npos) + continue; + line.remove_prefix(first); + if (!line.starts_with('/') && !line.starts_with("\"/")) + continue; + const auto words = printed_argv(line); + if (!words.empty() && fs::path{words.front()}.filename() == "cc1plus") + reference = words; + } + need(!reference.empty(), "could not identify the GCC C++ frontend"); + profile->frontend = fs::canonical(reference.front()); + std::set system; + for (std::size_t i = 0; i + 1 < reference.size(); ++i) + if (reference[i] == "-isystem" || reference[i] == "-idirafter" || + reference[i] == "-I") { + const fs::path directory = reference[i + 1]; + store_package(directory); + need(fs::is_directory(directory), + "the compiler reported a missing include directory"); + system.insert(directory); + } + auto [closure_status, closure_text] = + capture({"nix-store", "-qR", store_package(driver).native(), + store_package(profile->frontend).native(), + store_package(profile->strace).native()}); + need(closure_status == 0, "could not inspect the compiler runtime closure"); + std::set mounts{system}; + std::string_view closure = closure_text; + while (!closure.empty()) { + const auto end = closure.find('\n'); + const auto line = closure.substr(0, end); + closure.remove_prefix(end == std::string_view::npos ? closure.size() : end + 1); + if (line.empty()) + continue; + const fs::path package{line}; + need(store_package(package) == package, "unexpected tool runtime closure"); + mounts.insert(package); + } + need(!mounts.empty() && mounts.size() <= 256, "unexpected tool runtime closure"); + profile->mounts.assign(mounts.begin(), mounts.end()); + auto key = "NIX_CFLAGS_COMPILE_" + target; + std::ranges::replace(key, '-', '_'); + const char *raw = std::getenv(key.c_str()); + if (!raw) + raw = std::getenv("NIX_CFLAGS_COMPILE"); + const std::string environment = raw ? raw : ""; + auto append = [&](std::string_view word) { + if (!profile->flags.empty()) + profile->flags += ' '; + profile->flags += word; + }; + std::string_view words{environment}; + while (!words.empty()) { + const auto space = words.find(' '); + const auto word = words.substr(0, space); + words = space == std::string_view::npos ? std::string_view{} + : words.substr(space + 1); + if (word.empty()) + continue; + if (word.starts_with("-frandom-seed=")) { + need(word.size() <= 128 && + word.find_first_not_of( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._=", + 15) == std::string_view::npos, + "invalid toolchain seed"); + append(word); + } else if (word == "-isystem" || word == "-idirafter" || word == "-I") { + const auto next = words.find(' '); + const auto value = words.substr(0, next); + words = next == std::string_view::npos ? std::string_view{} + : words.substr(next + 1); + const fs::path directory{value}; + store_package(directory); + need(system.contains(directory), "unverified toolchain include option"); + append(word); + append(value); + } else { + throw std::runtime_error( + "the toolchain includes an unsupported environment flag"); + } + } + profile->target = target; + std::string material = target + "\n" + profile->driver.native() + "\n" + + profile->frontend.native() + "\n" + profile->flags; + for (const auto &mount : profile->mounts) + material += "\n" + mount.native(); + profile->identity = Documents::compute_content_hash(material).display_digest(); + return profile; + } catch (const std::exception &error) { + return std::unexpected(error.what()); + } +} + +} // namespace vls::semantic diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8069874..e2b270b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,23 +1,72 @@ -add_executable(vls_unit_tests FramingTests.cpp JsonTests.cpp LifecycleTests.cpp) -target_link_libraries(vls_unit_tests PRIVATE vls_protocol) -void_add_tests(vls_unit_tests) +function(vls_test_suite target) + add_executable(${target} ${ARGN}) + target_link_libraries(${target} PRIVATE vls_protocol Void::Testing) + set_target_properties(${target} PROPERTIES VOID_TESTING_NO_AUTO_SCAN TRUE) + add_test(NAME ${target} COMMAND ${target}) + set_tests_properties(${target} PROPERTIES TIMEOUT 30) +endfunction() -add_executable(vls_json_capabilities JsonCapabilities.cpp) -target_link_libraries(vls_json_capabilities PRIVATE vls_protocol Void::System) -target_compile_definitions(vls_json_capabilities PRIVATE "VLS_EXECUTABLE=\"$\"") -add_dependencies(vls_json_capabilities vls) -void_add_tests(vls_json_capabilities) +vls_test_suite(vls_unit_tests FramingTests.cpp JsonTests.cpp LifecycleTests.cpp ProtocolEncodingTests.cpp) +vls_test_suite(vls_json_capabilities JsonCapabilities.cpp) +vls_test_suite(vls_process_tests ProcessTests.cpp ProviderProcessTests.cpp) +vls_test_suite(vls_document_tests documents/DocumentTests.cpp documents/LongLineTests.cpp + documents/BoundInputTests.cpp) +vls_test_suite(vls_workspace_tests workspace/WorkspaceTests.cpp workspace/ProviderSessionTests.cpp + workspace/SemanticLeaseTests.cpp) +vls_test_suite(vls_build_model_tests providers/ModelTests.cpp) +vls_test_suite(vls_diagnostic_tests semantic/DiagnosticTests.cpp semantic/SourceCatalogTests.cpp + semantic/OccurrenceTests.cpp) +vls_test_suite(vls_module_tests modules/ModuleGraphTests.cpp modules/ArtifactCacheTests.cpp + modules/ModuleWorkQueueTests.cpp modules/ScanCommandTests.cpp) +vls_test_suite(vls_scheduler_tests scheduler/SchedulerTests.cpp) +vls_test_suite(vls_index_tests index/SymbolIndexTests.cpp) +vls_test_suite(vls_navigation_tests navigation/NavigationTests.cpp) +vls_test_suite(vls_reflection_tests reflection/ProvenanceTests.cpp) +vls_test_suite(vls_feature_tests features/CompletionTests.cpp features/IndexNavigationTests.cpp features/SignatureHelpTests.cpp) +vls_test_suite(vls_live_tests debug/LiveSessionTests.cpp debug/LiveDapTests.cpp) +target_link_libraries(vls_live_tests PRIVATE Void::System) +add_dependencies(vls_live_tests vls_live_worker_fixture vls-dap) +set_tests_properties(vls_live_tests PROPERTIES LABELS live-debug) +set_tests_properties(vls_scheduler_tests PROPERTIES LABELS scheduler) +set_tests_properties(vls_index_tests PROPERTIES LABELS index) +set_tests_properties(vls_navigation_tests PROPERTIES LABELS navigation-rename) +set_tests_properties(vls_reflection_tests PROPERTIES LABELS reflection) +set_tests_properties(vls_feature_tests PROPERTIES LABELS completion-hover) +set_tests_properties(vls_module_tests PROPERTIES LABELS module-graph) +set_tests_properties(vls_diagnostic_tests PROPERTIES LABELS gcc-diagnostics) +add_executable(vls_gcc_diagnostic_fixture semantic/GccDiagnosticFixture.cpp) +target_link_libraries(vls_gcc_diagnostic_fixture PRIVATE vls_protocol) +add_executable(vls_module_scan_fixture modules/GccScanFixture.cpp) +target_link_libraries(vls_module_scan_fixture PRIVATE vls_protocol) +add_executable(vls_live_worker_fixture debug/LiveWorkerFixture.cpp) +target_link_libraries(vls_live_worker_fixture PRIVATE vls_protocol) +add_executable(vls_module_artifact_fixture modules/ModuleArtifactFixture.cpp) +target_link_libraries(vls_module_artifact_fixture PRIVATE vls_protocol Void::System) +vls_test_suite(vls_trace_tests debug/TraceTests.cpp debug/RecordingTests.cpp) +target_link_libraries(vls_trace_tests PRIVATE vls_gcc_trace) +set_tests_properties(vls_trace_tests PROPERTIES LABELS trace-replay TIMEOUT 120) +vls_test_suite(vls_dap_tests debug/DapReplayTests.cpp) +target_link_libraries(vls_dap_tests PRIVATE vls_gcc_trace Void::System) +target_compile_definitions(vls_dap_tests PRIVATE "VLS_DAP_EXECUTABLE=\"$\"") +add_dependencies(vls_dap_tests vls-dap) +set_tests_properties(vls_dap_tests PROPERTIES LABELS "dap;inspection") +vls_test_suite(vls_provider_tests providers/ProviderFileTests.cpp providers/VbsProviderTests.cpp + providers/CompdbProviderTests.cpp providers/CommandImportTests.cpp) +set_tests_properties(vls_provider_tests PROPERTIES LABELS "vbs-provider;compdb") +set_tests_properties(vls_build_model_tests PROPERTIES LABELS build-model) +set_tests_properties(vls_document_tests PROPERTIES LABELS documents) +set_tests_properties(vls_workspace_tests PROPERTIES LABELS workspace) -add_executable(vls_process_tests ProcessTests.cpp) -target_link_libraries(vls_process_tests PRIVATE vls_protocol Void::System) -target_compile_definitions(vls_process_tests PRIVATE "VLS_EXECUTABLE=\"$\"") -add_dependencies(vls_process_tests vls) -void_add_tests(vls_process_tests) +foreach(target IN ITEMS vls_json_capabilities vls_process_tests) + target_link_libraries(${target} PRIVATE Void::System) + target_compile_definitions(${target} PRIVATE "VLS_EXECUTABLE=\"$\"") + add_dependencies(${target} vls) +endforeach() -set_tests_properties(vls_unit_tests vls_json_capabilities vls_process_tests PROPERTIES TIMEOUT 30) -add_test(NAME vls_test_registration COMMAND "${CMAKE_COMMAND}" - "-DUNIT=$" - "-DCAPABILITIES=$" - "-DPROCESS=$" - -P "${CMAKE_CURRENT_SOURCE_DIR}/Registration.cmake") +add_executable(vls_test_registration NativeRegistration.cpp) +target_link_libraries(vls_test_registration PRIVATE Void::System) +add_dependencies(vls_test_registration vls_unit_tests vls_json_capabilities vls_process_tests + vls_document_tests vls_workspace_tests vls_build_model_tests vls_provider_tests vls_trace_tests + vls_diagnostic_tests vls_module_tests vls_dap_tests vls_scheduler_tests vls_index_tests vls_navigation_tests vls_reflection_tests vls_feature_tests vls_live_tests) +add_test(NAME vls_test_registration COMMAND vls_test_registration) set_tests_properties(vls_test_registration PROPERTIES TIMEOUT 20) diff --git a/tests/FramingTests.cpp b/tests/FramingTests.cpp index 87e0a90..c4c39c5 100644 --- a/tests/FramingTests.cpp +++ b/tests/FramingTests.cpp @@ -2,7 +2,7 @@ #include -Void::Testing::Test consecutive_frames_preserve_byte_lengths() { +VOID_TEST(FramingTests, consecutive_frames_preserve_byte_lengths) { const std::string body{"\"\xF0\x9F\x98\x83\""}; std::istringstream input{test::frame(body) + test::frame("{}")}; auto first = vls::read_frame(input); @@ -15,7 +15,7 @@ Void::Testing::Test consecutive_frames_preserve_byte_lengths() { Void::Testing::expect(eof.has_value() && !eof->has_value()); } -Void::Testing::Test exact_frame_limits() { +VOID_TEST(FramingTests, exact_frame_limits) { const auto wire = test::frame("1234"); std::istringstream exact{wire}; Void::Testing::expect(vls::read_frame(exact, {wire.size() - 4, 4}).has_value()); @@ -25,7 +25,7 @@ Void::Testing::Test exact_frame_limits() { Void::Testing::expect(!vls::read_frame(body_over, {wire.size() - 4, 3}).has_value()); } -Void::Testing::Test length_validation() { +VOID_TEST(FramingTests, length_validation) { for (const std::string header : {"Other: 1", "Content-Length: ", "Content-Length: -1", "Content-Length: +1", "Content-Length: 1x", "Content-Length: 1 0", "Content-Length: 1.0", @@ -40,7 +40,7 @@ Void::Testing::Test length_validation() { Void::Testing::expect((**result).empty()); } -Void::Testing::Test charset_and_header_validation() { +VOID_TEST(FramingTests, charset_and_header_validation) { for (const std::string type : {"application/vscode-jsonrpc; charset=utf-8", "application/vscode-jsonrpc; charset=UTF8", "application/vscode-jsonrpc", "application/json; charset=\"utf-8\""}) { @@ -62,14 +62,14 @@ Void::Testing::Test charset_and_header_validation() { Void::Testing::expect(!vls::read_frame(non_ascii).has_value()); } -Void::Testing::Test truncated_header_and_body_are_fatal() { +VOID_TEST(FramingTests, truncated_header_and_body_are_fatal) { for (const std::string wire : {"C", "Content-Length: 2\r\n", "Content-Length: 2\r\n\r\n{"}) { std::istringstream input{wire}; Void::Testing::expect(!vls::read_frame(input).has_value()); } } -Void::Testing::Test stream_failures_propagate() { +VOID_TEST(FramingTests, stream_failures_propagate) { std::istringstream broken; broken.setstate(std::ios::badbit); Void::Testing::expect(!vls::read_frame(broken).has_value()); @@ -82,7 +82,7 @@ Void::Testing::Test stream_failures_propagate() { Void::Testing::expect(!diagnostics.str().empty()); } -Void::Testing::Test no_resynchronization_after_framing_error() { +VOID_TEST(FramingTests, no_resynchronization_after_framing_error) { std::istringstream input{"Content-Length: nope\r\n\r\n" + test::frame(test::initialize_request)}; std::ostringstream output; diff --git a/tests/JsonCapabilities.cpp b/tests/JsonCapabilities.cpp index c5fd02f..6e39afd 100644 --- a/tests/JsonCapabilities.cpp +++ b/tests/JsonCapabilities.cpp @@ -1,3 +1,4 @@ +#include "TestExecutable.hpp" #include "TestSupport.hpp" #include @@ -6,14 +7,14 @@ // These are upstream integration requirements, deliberately ordinary failing // tests until a verified StrictJson revision implements the complete grammar. -Void::Testing::Test decimal_and_exponent_json_values() { +VOID_TEST(JsonCapabilities, decimal_and_exponent_json_values) { for (const auto number : {"0.0", "-0.5", "1.25", "1e3", "1E+3", "-2.5e-2", "0e0"}) { const auto parsed = vls::parse_json(std::string{"{\"ignored\":"} + number + "}"); Void::Testing::expect(parsed.has_value()); } } -Void::Testing::Test decimal_initialization_options_and_unknown_fields() { +VOID_TEST(JsonCapabilities, decimal_initialization_options_and_unknown_fields) { for (const auto number : {"1.5", "-2.5e-2", "1E+3"}) { vls::Server server; const auto reply = test::response( @@ -28,7 +29,7 @@ Void::Testing::Test decimal_initialization_options_and_unknown_fields() { } } -Void::Testing::Test fractional_and_out_of_range_numeric_ids_are_invalid_requests() { +VOID_TEST(JsonCapabilities, fractional_and_out_of_range_numeric_ids_are_invalid_requests) { for (const auto id : {"1.5", "1e-1", "2147483648.0", "-2147483649.0", "1e50"}) { vls::Server server; const auto reply = test::response(server, std::string{"{\"jsonrpc\":\"2.0\",\"id\":"} + id + @@ -39,7 +40,7 @@ Void::Testing::Test fractional_and_out_of_range_numeric_ids_are_invalid_requests } } -Void::Testing::Test integer_valued_number_ids_preserve_value() { +VOID_TEST(JsonCapabilities, integer_valued_number_ids_preserve_value) { const std::pair cases[] = {{"1.0", 1}, {"1e0", 1}, {"-0.0", 0}, @@ -57,7 +58,7 @@ Void::Testing::Test integer_valued_number_ids_preserve_value() { } } -Void::Testing::Test numeric_ids_through_executable() { +VOID_TEST(JsonCapabilities, numeric_ids_through_executable) { using namespace std::chrono_literals; const auto input = test::frame(R"({"jsonrpc":"2.0","id":1e0,"method":"initialize","params":{}})") + @@ -66,7 +67,7 @@ Void::Testing::Test numeric_ids_through_executable() { test::frame(R"({"jsonrpc":"2.0","id":1.5,"method":"unknown"})") + test::frame(R"({"jsonrpc":"2.0","id":2.147483647e9,"method":"shutdown"})") + test::frame(test::exit); - const auto output = Void::Process::run(VLS_EXECUTABLE, {"--stdio"}, input, 2s); + const auto output = Void::Process::run(test::server_executable(), {"--stdio"}, input, 2s); Void::Testing::require(output.has_value()); Void::Testing::expect_eq(output->exit_code, 0); Void::Testing::expect(output->err.empty()); @@ -90,13 +91,13 @@ Void::Testing::Test numeric_ids_through_executable() { std::holds_alternative(test::field(replies[4], "result").value)); } -Void::Testing::Test decimal_initialization_through_executable() { +VOID_TEST(JsonCapabilities, decimal_initialization_through_executable) { using namespace std::chrono_literals; const auto input = test::frame( R"({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{},"initializationOptions":{"scale":1.5,"exponent":-2.5e-2},"unknown":1E+3}})") + test::frame(test::initialized) + test::frame(test::shutdown) + test::frame(test::exit); - const auto output = Void::Process::run(VLS_EXECUTABLE, {"--stdio"}, input, 2s); + const auto output = Void::Process::run(test::server_executable(), {"--stdio"}, input, 2s); Void::Testing::require(output.has_value()); Void::Testing::expect_eq(output->exit_code, 0); Void::Testing::expect(output->err.empty()); @@ -107,3 +108,39 @@ Void::Testing::Test decimal_initialization_through_executable() { Void::Testing::expect(object->contains("result")); Void::Testing::expect(!object->contains("error")); } + +VOID_TEST(JsonCapabilities, rounded_fractional_id_cannot_change_lifecycle) { + using namespace std::chrono_literals; + const auto input = + test::frame(test::initialize_request) + + test::frame(R"({"jsonrpc":"2.0","id":1.0000000000000001,"method":"shutdown"})") + + test::frame(R"({"jsonrpc":"2.0","id":1,"method":"shutdown"})") + test::frame(test::exit); + const auto child = Void::Process::run(test::server_executable(), {"--stdio"}, input, 2s); + Void::Testing::require(child.has_value()); + Void::Testing::expect_eq(child->exit_code, 0); + Void::Testing::expect(child->err.empty()); + const auto replies = test::responses(child->out); + Void::Testing::require_eq(replies.size(), std::size_t{3}); + Void::Testing::expect_eq(test::error_code(replies[1]), std::int64_t{-32600}); + Void::Testing::expect( + std::holds_alternative(test::field(replies[1], "id").value)); + Void::Testing::expect_eq(std::get(test::field(replies[2], "id").value), + std::int64_t{1}); + Void::Testing::expect( + std::holds_alternative(test::field(replies[2], "result").value)); +} + +VOID_TEST(JsonCapabilities, valid_number_outside_machine_range_is_still_json) { + vls::Server server; + test::expect_error(server, R"({"jsonrpc":"2.0","id":9223372036854775808,"method":"unknown"})", + -32600); + test::expect_error(server, R"({"jsonrpc":"2.0","id":1e,"method":"initialize","params":{}})", + -32700); + const auto initialized = test::response( + server, + R"({"jsonrpc":"2.0","id":7,"method":"initialize","params":{"initializationOptions":{"n":1e-400}}})"); + Void::Testing::expect(std::get(initialized.value).contains("result")); + const auto *id = std::get_if(&test::field(initialized, "id").value); + Void::Testing::require(id != nullptr); + Void::Testing::expect_eq(*id, std::int64_t{7}); +} diff --git a/tests/JsonTests.cpp b/tests/JsonTests.cpp index 56ea72f..4a9fbda 100644 --- a/tests/JsonTests.cpp +++ b/tests/JsonTests.cpp @@ -1,6 +1,6 @@ #include "TestSupport.hpp" -Void::Testing::Test valid_unicode_and_escapes() { +VOID_TEST(JsonTests, valid_unicode_and_escapes) { const auto pair = vls::parse_json(R"("\uD83D\uDE03")"); Void::Testing::require(pair.has_value()); Void::Testing::expect_eq(std::get(pair->value), std::string{"\xF0\x9F\x98\x83"}); @@ -12,7 +12,7 @@ Void::Testing::Test valid_unicode_and_escapes() { Void::Testing::expect_eq(std::get(round_trip->value), source); } -Void::Testing::Test rejects_invalid_utf8_and_raw_controls() { +VOID_TEST(JsonTests, rejects_invalid_utf8_and_raw_controls) { for (const std::string bytes : {std::string{"\x80"}, std::string{"\xC0\xAF"}, std::string{"\xE0\x80\xAF"}, std::string{"\xED\xA0\x80"}, std::string{"\xF4\x90\x80\x80"}, std::string{"\xF0\x9F"}, @@ -21,14 +21,14 @@ Void::Testing::Test rejects_invalid_utf8_and_raw_controls() { } } -Void::Testing::Test rejects_invalid_escapes_and_surrogates() { +VOID_TEST(JsonTests, rejects_invalid_escapes_and_surrogates) { for (const auto text : {R"("\uD800")", R"("\uDC00")", R"("\uD800\u0041")", R"("\uD800\uD800")", R"("\uDE03\uD83D")", R"("\uGGGG")", R"("\u12")", R"("\x20")", R"("unterminated)", R"("\")"}) Void::Testing::expect(!vls::parse_json(text).has_value()); } -Void::Testing::Test depth_is_bounded_before_recursive_parse() { +VOID_TEST(JsonTests, depth_is_bounded_before_recursive_parse) { Void::Testing::expect( vls::parse_json(std::string(64, '[') + "0" + std::string(64, ']')).has_value()); Void::Testing::expect( @@ -39,7 +39,7 @@ Void::Testing::Test depth_is_bounded_before_recursive_parse() { Void::Testing::expect(!vls::parse_json(std::string(100000, '[')).has_value()); } -Void::Testing::Test request_ids_preserve_strings_and_signed32_range() { +VOID_TEST(JsonTests, request_ids_preserve_strings_and_signed32_range) { for (const auto text : {"-2147483648", "2147483647", "0", "-1", R"("quote\"\\\n\u0416")"}) { const auto json = vls::parse_json(text); Void::Testing::require(json.has_value()); @@ -58,7 +58,7 @@ Void::Testing::Test request_ids_preserve_strings_and_signed32_range() { } } -Void::Testing::Test malformed_json_is_rejected() { +VOID_TEST(JsonTests, malformed_json_is_rejected) { for (const auto text : {"", "{} x", "{", "[1,]", "{\"a\":1,}", "true false", R"({"same":1,"same":2})", "01", "-", "NaN", "Infinity", "1.", "1e", "1e+", "+1", ".1", "--1"}) diff --git a/tests/LifecycleTests.cpp b/tests/LifecycleTests.cpp index ab47659..3b40f71 100644 --- a/tests/LifecycleTests.cpp +++ b/tests/LifecycleTests.cpp @@ -1,11 +1,10 @@ #include "TestSupport.hpp" -Void::Testing::Test complete_lifecycle_advertises_empty_capabilities() { +VOID_TEST(LifecycleTests, complete_lifecycle_advertises_document_sync) { vls::Server server; const auto initialized = test::response(server, test::initialize_request); const auto &result = test::field(initialized, "result"); - Void::Testing::expect( - std::get(test::field(result, "capabilities").value).empty()); + test::expect_sync_capabilities(result); const auto &info = test::field(result, "serverInfo"); Void::Testing::expect_eq(std::get(test::field(info, "name").value), std::string{"VoidLanguageServer"}); @@ -21,7 +20,7 @@ Void::Testing::Test complete_lifecycle_advertises_empty_capabilities() { Void::Testing::expect_eq(*exited.exit_code, 0); } -Void::Testing::Test requests_before_initialize_and_premature_exit() { +VOID_TEST(LifecycleTests, requests_before_initialize_and_premature_exit) { vls::Server server; test::expect_error(server, test::shutdown, -32002); test::expect_error(server, R"({"jsonrpc":"2.0","id":3,"method":"unknown"})", -32002); @@ -31,7 +30,7 @@ Void::Testing::Test requests_before_initialize_and_premature_exit() { Void::Testing::expect_eq(*exited.exit_code, 1); } -Void::Testing::Test initialize_requires_object_and_only_runs_once() { +VOID_TEST(LifecycleTests, initialize_requires_object_and_only_runs_once) { vls::Server server; for (const auto params : {"", ",\"params\":[]", ",\"params\":null", ",\"params\":true"}) test::expect_error( @@ -43,7 +42,7 @@ Void::Testing::Test initialize_requires_object_and_only_runs_once() { test::expect_error(server, test::initialize_request, -32600); } -Void::Testing::Test unknown_methods_notifications_and_exit_request() { +VOID_TEST(LifecycleTests, unknown_methods_notifications_and_exit_request) { vls::Server server; test::initialize(server); test::expect_error( @@ -56,7 +55,7 @@ Void::Testing::Test unknown_methods_notifications_and_exit_request() { Void::Testing::expect_eq(*server.handle(test::exit).exit_code, 1); } -Void::Testing::Test post_shutdown_precedes_all_request_methods() { +VOID_TEST(LifecycleTests, post_shutdown_precedes_all_request_methods) { vls::Server server; test::initialize(server); static_cast(test::response(server, test::shutdown)); @@ -66,7 +65,7 @@ Void::Testing::Test post_shutdown_precedes_all_request_methods() { Void::Testing::expect_eq(*server.handle(test::exit).exit_code, 0); } -Void::Testing::Test malformed_envelopes_and_ids() { +VOID_TEST(LifecycleTests, malformed_envelopes_and_ids) { vls::Server server; for (const auto text : {"[]", "[{}]", "null", "true", "{}", R"({"jsonrpc":"1.0","id":1,"method":"initialize"})", @@ -86,7 +85,7 @@ Void::Testing::Test malformed_envelopes_and_ids() { std::string{"\"\xD0\x96\n"}); } -Void::Testing::Test unmatched_responses_do_not_reply_or_change_lifecycle() { +VOID_TEST(LifecycleTests, unmatched_responses_do_not_reply_or_change_lifecycle) { vls::Server server; const auto ignore_responses = [&] { for (const auto text : @@ -108,7 +107,7 @@ Void::Testing::Test unmatched_responses_do_not_reply_or_change_lifecycle() { Void::Testing::expect_eq(*server.handle(test::exit).exit_code, 0); } -Void::Testing::Test parse_errors_use_null_id_and_do_not_mutate_state() { +VOID_TEST(LifecycleTests, parse_errors_use_null_id_and_do_not_mutate_state) { vls::Server server; const auto malformed = test::response(server, "{bad"); Void::Testing::expect_eq(test::error_code(malformed), std::int64_t{-32700}); @@ -119,7 +118,7 @@ Void::Testing::Test parse_errors_use_null_id_and_do_not_mutate_state() { static_cast(test::response(server, test::shutdown)); } -Void::Testing::Test eof_never_reports_success_without_exit() { +VOID_TEST(LifecycleTests, eof_never_reports_success_without_exit) { for (const auto wire : {std::string{}, test::frame(test::initialize_request), test::frame(test::initialize_request) + test::frame(test::shutdown)}) { std::istringstream input{wire}; diff --git a/tests/NativeRegistration.cpp b/tests/NativeRegistration.cpp new file mode 100644 index 0000000..e67cb59 --- /dev/null +++ b/tests/NativeRegistration.cpp @@ -0,0 +1,74 @@ +#include + +#include +#include +#include +#include +#include +#include + +int main() { + using namespace std::chrono_literals; + const auto bin = std::filesystem::read_symlink("/proc/self/exe").parent_path(); + struct Inventory { + const char *target; + std::size_t minimum; + const char *witness; + }; + for (const auto &[target, minimum, witness] : { + Inventory{"vls_unit_tests", 29, + "ProtocolEncodingTests.default_depth_counts_empty_containers"}, + Inventory{"vls_json_capabilities", 8, + "JsonCapabilities.rounded_fractional_id_cannot_change_lifecycle"}, + Inventory{"vls_process_tests", 18, + "ProviderProcess.database_binds_the_physical_translation_unit"}, + Inventory{"vls_document_tests", 37, + "BoundInputs.empty_inventory_detects_a_new_unsaved_header"}, + Inventory{ + "vls_workspace_tests", 46, + "SemanticLease.checked_compdb_command_and_selection_survive_unchanged_status"}, + Inventory{ + "vls_build_model_tests", 18, + "BuildModel.selection_preserves_conflicting_commands_and_follows_precedence"}, + Inventory{ + "vls_diagnostic_tests", 29, + "SourceCatalogTests.first_missing_directory_invalidates_deeper_optional_lookup"}, + Inventory{"vls_module_tests", 22, + "ModuleGraph.noninterface_named_provision_requires_a_partition"}, + Inventory{"vls_dap_tests", 7, + "DapReplay.deferred_launch_finishes_after_configuration_done"}, + Inventory{"vls_provider_tests", 42, + "CommandImport.physical_owners_follow_links_before_parent_components"}, + Inventory{"vls_reflection_tests", 24, "Reflection.virtual_view_links_source_ranges"}, + Inventory{"vls_trace_tests", 21, + "RecordingTests.retains_values_and_source_across_overwrite_replacement_and_" + "unlink"}, + }) { + auto listed = Void::Process::run(bin / target, {"--list", "--no-color"}, {}, 5s); + if (!listed || listed->exit_code != 0 || !listed->err.empty()) { + std::cerr << "Could not enumerate " << target << '\n'; + return 1; + } + std::set names; + std::istringstream lines{listed->out}; + for (std::string name; std::getline(lines, name);) { + if (name.empty() || !names.insert(name).second) { + std::cerr << target << " returned an empty or duplicate case name\n"; + return 1; + } + } + if (names.size() < minimum || !names.contains(witness)) { + std::cerr << target << " has an incomplete inventory (" << names.size() << " cases)\n"; + return 1; + } + } + auto ran = + Void::Process::run(bin / "vls_unit_tests", + {"--no-color", "--filter", "^FramingTests.exact_frame_limits$"}, {}, 5s); + if (!ran || ran->exit_code != 0 || !ran->out.contains("1 tests:") || + !ran->out.contains("exact_frame_limits")) { + std::cerr << "The named framing regression did not execute successfully\n"; + return 1; + } + return 0; +} diff --git a/tests/ProcessTests.cpp b/tests/ProcessTests.cpp index f699d13..d30c89c 100644 --- a/tests/ProcessTests.cpp +++ b/tests/ProcessTests.cpp @@ -1,11 +1,14 @@ +#include "TestExecutable.hpp" #include "TestSupport.hpp" #include +#include #include #include #include #include +#include #include namespace { @@ -13,7 +16,7 @@ using namespace std::chrono_literals; Void::Process::Child spawn(const std::vector &arguments = {}) { Void::Process::SpawnOptions options; - options.executable = VLS_EXECUTABLE; + options.executable = test::server_executable(); options.arguments = arguments; options.search_path = false; options.kill_grace = 100ms; @@ -96,9 +99,21 @@ std::string lifecycle() { test::frame(test::shutdown) + test::frame(test::exit); } +constexpr std::string_view open_document = + R"({"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"untitled:sync","languageId":"cpp","version":1,"text":"a"}}})"; +constexpr std::string_view close_document = + R"({"jsonrpc":"2.0","method":"textDocument/didClose","params":{"textDocument":{"uri":"untitled:sync"}}})"; + +std::string change_document(int version, std::string_view changes) { + return test::frame( + std::string{ + R"({"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"untitled:sync","version":)"} + + std::to_string(version) + R"(},"contentChanges":)" + std::string{changes} + "}}"); +} + } // namespace -Void::Testing::Test cli_standalone_and_invalid_modes() { +VOID_TEST(ProcessTests, cli_standalone_and_invalid_modes) { for (const auto flag : {"--help", "-h", "--version", "-V"}) { const auto output = run({}, {flag}); Void::Testing::expect_eq(output.status.code, 0); @@ -127,7 +142,7 @@ Void::Testing::Test cli_standalone_and_invalid_modes() { } } -Void::Testing::Test default_and_explicit_stdio_lifecycle() { +VOID_TEST(ProcessTests, default_and_explicit_stdio_lifecycle) { for (const auto &args : std::vector>{{}, {"--stdio"}}) { const auto output = run(lifecycle(), args); Void::Testing::expect_eq(output.status.code, 0); @@ -135,14 +150,82 @@ Void::Testing::Test default_and_explicit_stdio_lifecycle() { const auto replies = test::responses(output.out); Void::Testing::require_eq(replies.size(), std::size_t{2}); const auto &result = test::field(replies[0], "result"); - Void::Testing::expect( - std::get(test::field(result, "capabilities").value).empty()); + test::expect_sync_capabilities(result); Void::Testing::expect( std::holds_alternative(test::field(replies[1], "result").value)); } } -Void::Testing::Test fragmented_headers_bodies_and_immediate_flush() { +VOID_TEST(ProcessTests, negotiated_incremental_edit_observes_astral_character) { + constexpr auto replace = + R"([{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"text":"\uD83D\uDE42"}])"; + constexpr auto split = + R"([{"range":{"start":{"line":0,"character":1},"end":{"line":0,"character":1}},"text":"x"}])"; + for (const auto &[offered, encoding, diagnostic] : + {std::tuple{R"(["utf-32","utf-8","utf-16"])", "utf-8", "splits a Unicode scalar"}, + std::tuple{R"(["utf-16","utf-8"])", "utf-16", "splits a surrogate pair"}}) { + const auto initialize = test::frame( + std::string{ + R"({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{"general":{"positionEncodings":)"} + + offered + "}}}}"); + auto output = run(initialize + test::frame(test::initialized) + test::frame(open_document) + + change_document(2, replace) + change_document(3, split) + + test::frame(close_document) + test::frame(test::shutdown) + + test::frame(test::exit)); + Void::Testing::expect_eq(output.status.code, 0); + auto replies = test::responses(output.out); + Void::Testing::require_eq(replies.size(), std::size_t{2}); + test::expect_sync_capabilities(test::field(replies[0], "result"), encoding); + Void::Testing::expect(output.err.contains(diagnostic)); + Void::Testing::expect_eq(std::ranges::count(output.err, '\n'), 1); + } +} + +VOID_TEST(ProcessTests, malformed_batch_blocks_edits_until_newer_full_replacement) { + constexpr auto malformed = R"([{"text":"old"},{"text":"bad","range":null}])"; + constexpr auto full = R"([{"text":"a"}])"; + constexpr auto ranged = + R"([{"text":"b","range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}}}])"; + constexpr auto overflow = + R"([{"text":"","range":{"start":{"line":0,"character":2147483648},"end":{"line":0,"character":2147483648}}}])"; + auto output = + run(test::frame(test::initialize_request) + test::frame(test::initialized) + + test::frame(open_document) + change_document(12, malformed) + + change_document(10, full) + change_document(13, ranged) + change_document(14, full) + + change_document(15, ranged) + change_document(16, overflow) + + change_document(17, full) + test::frame(close_document) + change_document(18, ranged) + + test::frame(test::shutdown) + test::frame(open_document) + test::frame(test::exit)); + Void::Testing::expect_eq(output.status.code, 0); + const auto replies = test::responses(output.out); + Void::Testing::require_eq(replies.size(), std::size_t{2}); + test::expect_sync_capabilities(test::field(replies[0], "result")); + Void::Testing::expect(output.err.contains("invalid change range")); + Void::Testing::expect(output.err.contains("nonmonotonic")); + Void::Testing::expect(output.err.contains("newer full-text replacement")); + Void::Testing::expect(output.err.contains("document is not open")); + Void::Testing::expect_eq(std::ranges::count(output.err, '\n'), 5); +} + +VOID_TEST(ProcessTests, malformed_change_envelope_invalidates_an_identifiable_document) { + const auto hybrid = test::frame( + R"({"jsonrpc":"2.0","method":"textDocument/didChange","result":null,"params":{"textDocument":{"uri":"untitled:sync","version":12},"contentChanges":[{"text":"bad"}]}})"); + constexpr auto ranged = + R"([{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"text":"b"}])"; + constexpr auto full = R"([{"text":"a"}])"; + auto output = + run(test::frame(test::initialize_request) + test::frame(test::initialized) + + test::frame(open_document) + hybrid + change_document(10, full) + + change_document(13, ranged) + change_document(14, full) + change_document(15, ranged) + + test::frame(close_document) + test::frame(test::shutdown) + test::frame(test::exit)); + Void::Testing::expect_eq(output.status.code, 0); + Void::Testing::require_eq(test::responses(output.out).size(), std::size_t{2}); + Void::Testing::expect(output.err.contains("invalid didChange envelope")); + Void::Testing::expect(output.err.contains("nonmonotonic")); + Void::Testing::expect(output.err.contains("newer full-text replacement")); + Void::Testing::expect_eq(std::ranges::count(output.err, '\n'), 3); +} + +VOID_TEST(ProcessTests, fragmented_headers_bodies_and_immediate_flush) { auto child = spawn({"--stdio"}); const auto input = test::frame(test::initialize_request); const auto split = input.find("\r\n\r\n") + 5; @@ -167,7 +250,7 @@ Void::Testing::Test fragmented_headers_bodies_and_immediate_flush() { Void::Testing::expect_eq(test::error_code(replies[1]), std::int64_t{-32601}); } -Void::Testing::Test unmatched_peer_responses_do_not_create_reply_loops() { +VOID_TEST(ProcessTests, unmatched_peer_responses_do_not_create_reply_loops) { const auto responses = test::frame(R"({"jsonrpc":"2.0","id":77,"result":{"ok":true}})") + test::frame(R"({"jsonrpc":"2.0","id":null,"result":null})") + @@ -187,7 +270,7 @@ Void::Testing::Test unmatched_peer_responses_do_not_create_reply_loops() { std::holds_alternative(test::field(replies[1], "result").value)); } -Void::Testing::Test known_size_malformed_json_continues() { +VOID_TEST(ProcessTests, known_size_malformed_json_continues) { const auto output = run(test::frame("{bad") + test::frame("[{}]") + lifecycle()); Void::Testing::expect_eq(output.status.code, 0); Void::Testing::expect(output.err.empty()); @@ -199,7 +282,7 @@ Void::Testing::Test known_size_malformed_json_continues() { Void::Testing::expect_eq(test::error_code(replies[1]), std::int64_t{-32600}); } -Void::Testing::Test invalid_encoding_and_surrogates_continue() { +VOID_TEST(ProcessTests, invalid_encoding_and_surrogates_continue) { const auto output = run(test::frame(std::string{"\"\xED\xA0\x80\""}) + test::frame(R"({"bad":"\uDC00"})") + lifecycle()); Void::Testing::expect_eq(output.status.code, 0); @@ -209,7 +292,7 @@ Void::Testing::Test invalid_encoding_and_surrogates_continue() { Void::Testing::expect_eq(test::error_code(replies[1]), std::int64_t{-32700}); } -Void::Testing::Test framing_errors_exit_without_resynchronization() { +VOID_TEST(ProcessTests, framing_errors_exit_without_resynchronization) { for (const auto prefix : {"Content-Length: invalid\r\n\r\n", "Other: 2\r\n\r\n", "Content-Length: 16777217\r\n\r\n", "Content-Length: 1\r\nContent-Length: 1\r\n\r\n", @@ -227,7 +310,7 @@ Void::Testing::Test framing_errors_exit_without_resynchronization() { } } -Void::Testing::Test premature_exit_and_unexpected_eof() { +VOID_TEST(ProcessTests, premature_exit_and_unexpected_eof) { for (const auto input : {std::string{}, test::frame(test::exit), test::frame(test::initialize_request) + test::frame(test::exit), test::frame(test::initialize_request) + test::frame(test::shutdown)}) { @@ -238,7 +321,7 @@ Void::Testing::Test premature_exit_and_unexpected_eof() { } } -Void::Testing::Test lifecycle_error_precedence_and_string_ids() { +VOID_TEST(ProcessTests, lifecycle_error_precedence_and_string_ids) { const auto output = run(test::frame(test::shutdown) + test::frame(test::initialize_request) + test::frame(test::initialize_request) + test::frame(R"({"jsonrpc":"2.0","id":"\"\u0416","method":"unknown"})") + diff --git a/tests/ProtocolEncodingTests.cpp b/tests/ProtocolEncodingTests.cpp new file mode 100644 index 0000000..a0bb90f --- /dev/null +++ b/tests/ProtocolEncodingTests.cpp @@ -0,0 +1,184 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Protocol = Void::LanguageServer::Protocol; +namespace Testing = Void::Testing; +using Protocol::Json; + +namespace { + +void expect_encoding_failure(const Json &value, std::string_view message, + std::size_t maximum_depth = Protocol::kDefaultMaxJsonDepth) { + const auto encoded = Protocol::serialize_json(value, maximum_depth); + Testing::require(!encoded.has_value()); + Testing::expect(encoded.error().contains(message)); + + std::ostringstream output; + const auto written = Protocol::write_json_frame(output, value, maximum_depth); + Testing::require(!written.has_value()); + Testing::expect_eq(written.error(), encoded.error()); + Testing::expect(output.str().empty()); +} + +Json nest_in_arrays(Json leaf, std::size_t count) { + for (std::size_t i = 0; i < count; ++i) { + Json::Array parent; + parent.push_back(std::move(leaf)); + leaf = Json{std::move(parent)}; + } + return leaf; +} + +} // namespace + +VOID_TEST(ProtocolEncodingTests, typed_response_round_trips_through_frame) { + const Protocol::RequestId id{std::string{"id\"\\\r\xF0\x9F\x98\x83"}}; + const std::string key{"key\"\n\\\xD0\x96"}; + std::string text{"quote\" slash\\\b\f\n\r\t"}; + text.push_back('\0'); + text += "\xD0\x96\xF0\x9F\x98\x83"; + Json::Array values{Json{1.25}, Json{nullptr}, Json{false}, Json{Json::Object{}}}; + Json::Object result{{key, Json{text}}, {"values", Json{std::move(values)}}}; + const Json response{Json::Object{{"jsonrpc", Json{std::string{"2.0"}}}, + {"id", Protocol::request_id_json(id)}, + {"result", Json{std::move(result)}}}}; + + std::ostringstream output; + const auto written = Protocol::write_json_frame(output, response); + Testing::require(written.has_value()); + const auto wire = output.str(); + std::istringstream input{wire}; + const auto frame = Protocol::read_frame(input); + Testing::require(frame.has_value() && frame->has_value()); + const auto &body = **frame; + Testing::expect_eq(wire, "Content-Length: " + std::to_string(body.size()) + "\r\n\r\n" + body); + const auto eof = Protocol::read_frame(input); + Testing::expect(eof.has_value() && !eof->has_value()); + + const auto decoded = Protocol::parse_json(body); + Testing::require(decoded.has_value()); + const auto *decoded_response = Protocol::as_object(&*decoded); + Testing::require(decoded_response != nullptr); + const auto *decoded_id = Protocol::find_member(*decoded_response, "id"); + Testing::require(decoded_id != nullptr); + const auto checked_id = Protocol::request_id(*decoded_id); + Testing::require(checked_id.has_value()); + Testing::expect_eq(*checked_id, id); + const auto *decoded_result = + Protocol::as_object(Protocol::find_member(*decoded_response, "result")); + Testing::require(decoded_result != nullptr); + const auto *decoded_text = Protocol::as_string(Protocol::find_member(*decoded_result, key)); + Testing::require(decoded_text != nullptr); + Testing::expect_eq(*decoded_text, text); + const auto *decoded_values = + Protocol::as_array(Protocol::find_member(*decoded_result, "values")); + Testing::require(decoded_values && decoded_values->size() == 4); + const auto *decimal = std::get_if(&(*decoded_values)[0].value); + Testing::require(decimal != nullptr); + Testing::expect_eq(*decimal, 1.25); + Testing::expect(std::holds_alternative((*decoded_values)[1].value)); + Testing::expect_eq(Protocol::as_bool(&(*decoded_values)[2]), std::optional{false}); + const auto *empty = Protocol::as_object(&(*decoded_values)[3]); + Testing::expect(empty && empty->empty()); +} + +VOID_TEST(ProtocolEncodingTests, invalid_utf8_in_key_or_value_writes_no_frame) { + const std::string invalid{"\xED\xA0\x80"}; + expect_encoding_failure(Json{Json::Array{Json{true}, Json{invalid}}}, "UTF-8"); + expect_encoding_failure(Json{Json::Object{{"ok", Json{true}}, {invalid, Json{nullptr}}}}, + "UTF-8"); + Testing::expect(!Protocol::parse_json("{\"" + invalid + "\":null}").has_value()); + Testing::expect(!Protocol::parse_json("[\"" + invalid + "\"]").has_value()); +} + +VOID_TEST(ProtocolEncodingTests, nonfinite_numbers_write_no_frame) { + for (const double number : + {std::numeric_limits::quiet_NaN(), std::numeric_limits::infinity(), + -std::numeric_limits::infinity()}) { + expect_encoding_failure(Json{Json::Array{Json{true}, Json{number}}}, "non-finite"); + } +} + +VOID_TEST(ProtocolEncodingTests, default_depth_counts_empty_containers) { + const auto encoded = Protocol::serialize_json(nest_in_arrays(Json{Json::Object{}}, 63)); + Testing::require(encoded.has_value()); + Testing::expect(Protocol::parse_json(*encoded).has_value()); + const auto encoded_scalar = Protocol::serialize_json(nest_in_arrays(Json{nullptr}, 64)); + Testing::require(encoded_scalar.has_value()); + Testing::expect(Protocol::parse_json(*encoded_scalar).has_value()); + + expect_encoding_failure(nest_in_arrays(Json{Json::Object{}}, 64), "depth limit"); + Testing::expect( + !Protocol::parse_json(std::string(64, '[') + "{}" + std::string(64, ']')).has_value()); +} + +VOID_TEST(ProtocolEncodingTests, custom_depth_counts_containers_and_accepts_root_scalars) { + for (const auto text : {"null", "false", "1.25", R"("[{}]")"}) { + const auto decoded = Protocol::parse_json(text, 0); + Testing::require(decoded.has_value()); + const auto encoded = Protocol::serialize_json(*decoded, 0); + Testing::require(encoded.has_value()); + Testing::expect_eq(*encoded, std::string{text}); + } + expect_encoding_failure(Json{Json::Array{}}, "depth limit", 0); + expect_encoding_failure(Json{Json::Object{}}, "depth limit", 0); + Testing::expect(!Protocol::parse_json("[]", 0).has_value()); + Testing::expect(!Protocol::parse_json("{}", 0).has_value()); + Testing::expect(Protocol::parse_json("[0]", 1).has_value()); + Testing::expect( + Protocol::serialize_json(nest_in_arrays(Json{std::int64_t{0}}, 1), 1).has_value()); + expect_encoding_failure(nest_in_arrays(Json{Json::Object{}}, 1), "depth limit", 1); + Testing::expect(!Protocol::parse_json("[{}]", 1).has_value()); +} + +VOID_TEST(ProtocolEncodingTests, oversized_depth_setting_stays_bounded) { + constexpr auto maximum_depth = std::numeric_limits::max(); + expect_encoding_failure(nest_in_arrays(Json{nullptr}, 512), "depth limit", maximum_depth); + Testing::expect( + !Protocol::parse_json(std::string(512, '[') + "null" + std::string(512, ']'), maximum_depth) + .has_value()); +} + +VOID_TEST(ProtocolEncodingTests, numeric_accessors_and_typed_ids_check_ranges) { + constexpr auto min_int64 = std::numeric_limits::min(); + constexpr auto max_int64 = std::numeric_limits::max(); + const Json lower_double{-0x1p63}; + const Json upper_double{0x1p63}; + const Json upper_integer{max_int64}; + Testing::expect_eq(Protocol::as_int64(&lower_double), std::optional{min_int64}); + Testing::expect(!Protocol::as_int64(&upper_double).has_value()); + Testing::expect_eq(Protocol::as_int64(&upper_integer), std::optional{max_int64}); + + constexpr auto max_uint32 = std::numeric_limits::max(); + const Json max_unsigned{static_cast(max_uint32)}; + const Json out_of_unsigned_range{static_cast(max_uint32) + 1}; + const Json negative{std::int64_t{-1}}; + Testing::expect_eq(Protocol::as_uint32(&max_unsigned), std::optional{max_uint32}); + Testing::expect(!Protocol::as_uint32(&out_of_unsigned_range).has_value()); + Testing::expect(!Protocol::as_uint32(&negative).has_value()); + + for (const auto number : + {std::numeric_limits::min(), std::numeric_limits::max()}) { + const auto id = Protocol::request_id(Json{static_cast(number)}); + Testing::require(id.has_value()); + Testing::expect_eq(*id, Protocol::RequestId{number}); + const auto encoded = Protocol::request_id_json(*id); + Testing::expect(std::holds_alternative(encoded.value)); + Testing::expect_eq(Protocol::as_int64(&encoded), std::optional{number}); + } + for (const Json &invalid : {Json{false}, Json{nullptr}, Json{1.25}, Json{2147483648.0}}) { + Testing::expect(!Protocol::request_id(invalid).has_value()); + } +} diff --git a/tests/ProviderProcessTests.cpp b/tests/ProviderProcessTests.cpp new file mode 100644 index 0000000..5c211ef --- /dev/null +++ b/tests/ProviderProcessTests.cpp @@ -0,0 +1,228 @@ +#include "TestExecutable.hpp" +#include "TestSupport.hpp" +#include "providers/ProviderFixture.hpp" + +#include +#include + +#include + +namespace { +using namespace provider_test; +using Void::LanguageServer::Documents::path_to_file_uri; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; +using Void::Testing::require_eq; + +std::string message(std::string_view method, Json::Object params, std::optional id) { + Json::Object object{ + {"jsonrpc", str("2.0")}, {"method", str(method)}, {"params", Json{std::move(params)}}}; + if (id) + object.emplace("id", Json{*id}); + auto bytes = Protocol::serialize_json(Json{std::move(object)}); + require(bytes.has_value()); + return test::frame(*bytes); +} + +Json folder(const Fixture &fixture) { + return Json{ + Json::Object{{"uri", str(path_to_file_uri(fixture.root))}, {"name", str("Project")}}}; +} + +std::string initialization(Json::Array folders) { + return message("initialize", + {{"capabilities", Json{Json::Object{}}}, + {"workspaceFolders", Json{std::move(folders)}}}, + 1) + + test::frame(test::initialized); +} + +std::string status(const Fixture &fixture, std::int64_t id, const fs::path &document = {}) { + const auto &source = document.empty() ? fixture.source : document; + return message("voidLanguageServer/providerStatus", + {{"workspaceUri", str(path_to_file_uri(fixture.root))}, + {"textDocument", Json{Json::Object{{"uri", str(path_to_file_uri(source))}}}}}, + id); +} + +std::vector transcript(std::string wire, std::vector args = {}) { + using namespace std::chrono_literals; + Void::Process::SpawnOptions options; + options.executable = test::server_executable(); + options.arguments = std::move(args); + options.search_path = false; + auto child = Void::Process::spawn(options); + require(child.has_value()); + wire += test::frame(test::shutdown) + test::frame(test::exit); + Void::Process::CaptureLimits limits; + limits.max_stdin_bytes = 65536; + limits.max_stdout_bytes = 131072; + limits.max_stderr_bytes = 16384; + auto result = Void::Process::communicate_blocking(*child, wire, limits, 5s); + require(result.has_value()); + require(result->status.exited && !result->timed_out && !result->cancelled && + !result->overflowed); + expect_eq(result->status.code, 0); + expect(result->err.empty()); + return test::responses(result->out); +} + +const std::string &string_field(const Json &record, std::string_view name) { + return std::get(test::field(record, name).value); +} + +void expect_ready(const Json &reply, const Fixture &fixture, std::string_view provider) { + const auto &result = test::field(reply, "result"); + expect_eq(string_field(result, "workspaceUri"), path_to_file_uri(fixture.root)); + expect_eq(string_field(result, "provider"), std::string{provider}); + expect_eq(string_field(result, "state"), std::string{"ready"}); + expect_eq(std::get(test::field(result, "contextCount").value), std::int64_t{2}); + expect_eq(std::get(test::field(result, "alternatives").value).size(), + std::size_t{2}); + expect(std::holds_alternative(test::field(result, "selected").value)); +} +} // namespace + +VOID_TEST(ProviderProcess, native_and_compatibility_workspaces_share_one_stdio_session) { + Fixture native, ordinary; + native.publish(); + const auto executable = ordinary.root / "marker-compiler"; + write_bytes(executable, "#!/bin/sh\nprintf called > \"$0.called\"\n"); + fs::permissions(executable, fs::perms::owner_exec, fs::perm_options::add); + auto rows = ordinary.rows(); + for (auto &row : rows) { + auto &argv = std::get(std::get(row.value).at("arguments").value); + argv.front() = str(executable.string()); + } + write_json(ordinary.compdb, Json{std::move(rows)}); + const auto replies = transcript(initialization({folder(native), folder(ordinary)}) + + status(native, 10) + status(ordinary, 11)); + require_eq(replies.size(), std::size_t{4}); + test::expect_sync_capabilities(test::field(replies.front(), "result")); + expect_ready(replies[1], native, "vbs"); + const auto &result = test::field(replies[1], "result"); + expect_eq(string_field(result, "nativeGeneration"), std::string{Fixture::first}); + expect_eq(string_field(result, "profile"), std::string{"debug"}); + expect_ready(replies[2], ordinary, "compdb"); + expect(!fs::exists(ordinary.root / "marker-compiler.called")); +} + +VOID_TEST(ProviderProcess, stale_native_selection_owns_one_root_with_an_available_database) { + Fixture native, ordinary; + native.publish(); + auto stale = native.valid_status(); + stale["status"] = str("stale"); + stale["diagnostic"] = str("generation unavailable"); + stale.erase("entry_count"); + stale.erase("readiness_warnings"); + write_json(native.editor() / "status.json", Json{std::move(stale)}); + write_json(native.compdb, Json{native.rows()}); + write_json(ordinary.compdb, Json{ordinary.rows()}); + const auto wire = initialization({folder(native), folder(ordinary)}) + status(native, 10) + + status(ordinary, 11); + for (const auto &args : std::vector>{ + {}, {"--workspace-root", native.root.string(), "--provider", "vbs"}}) { + const auto replies = transcript(wire, args); + require_eq(replies.size(), std::size_t{4}); + const auto &result = test::field(replies[1], "result"); + expect_eq(string_field(result, "provider"), std::string{"vbs"}); + expect_eq(string_field(result, "providerHealth"), std::string{"stale"}); + expect_eq(std::get(test::field(result, "contextCount").value), + std::int64_t{0}); + expect_ready(replies[2], ordinary, "compdb"); + } +} + +VOID_TEST(ProviderProcess, missing_external_database_directory_does_not_disable_native_selection) { + Fixture native, external; + native.publish(); + const auto future_db = external.root / "future-build/compile_commands.json"; + const std::vector launcher{"--workspace-root", native.root.string(), "--compdb", + future_db.string()}; + const auto wire = initialization({folder(native)}) + status(native, 9); + for (auto provider : {"auto", "vbs", "compdb"}) { + auto args = launcher; + args.insert(args.end(), {"--provider", provider}); + const auto replies = transcript(wire, args); + require_eq(replies.size(), std::size_t{3}); + if (std::string_view{provider} != "compdb") { + expect_ready(replies[1], native, "vbs"); + } else { + const auto &result = test::field(replies[1], "result"); + expect_eq(string_field(result, "state"), std::string{"degraded"}); + expect_eq(string_field(result, "provider"), std::string{"compdb"}); + } + } +} + +VOID_TEST(ProviderProcess, database_binds_the_physical_translation_unit) { + Fixture f; + const auto owner = f.root / "real/main.cpp"; + const auto alias = f.root / "alias.cpp"; + write_bytes(owner, "int real;\n"); + fs::create_directory(f.root / "real/sub"); + fs::create_directory_symlink("real/sub", f.root / "link"); + fs::create_symlink("real/main.cpp", alias); + Json::Array rows; + for (const auto *file : {"link/../main.cpp", "alias.cpp"}) { + rows.emplace_back( + Json::Object{{"directory", str(f.root.string())}, + {"file", str(file)}, + {"arguments", Json{Json::Array{str("c++"), str("-c"), str(file)}}}}); + } + write_json(f.compdb, Json{std::move(rows)}); + const auto replies = transcript(initialization({folder(f)}) + status(f, 10) + + status(f, 11, owner) + status(f, 12, alias)); + require_eq(replies.size(), std::size_t{5}); + const auto &innocent = test::field(replies[1], "result"); + expect(std::holds_alternative(test::field(innocent, "selected").value)); + expect(std::get(test::field(innocent, "alternatives").value).empty()); + for (const auto i : {2, 3}) { + expect_ready(replies[i], f, "compdb"); + const auto &selection = test::field(test::field(replies[i], "result"), "selected"); + expect_eq(string_field(selection, "owningTu"), path_to_file_uri(owner)); + } +} + +VOID_TEST(ProviderProcess, untraversable_document_spellings_do_not_select_a_real_file) { + Fixture f; + write_json(f.compdb, Json{f.rows()}); + fs::create_symlink("missing-target", f.root / "dangling"); + write_bytes(f.root / "ordinary", "file\n"); + auto wire = initialization({folder(f)}); + std::int64_t id = 10; + for (const auto *parent : {"missing", "dangling", "ordinary"}) + wire += status(f, id++, f.root / parent / ".." / "main.cpp"); + const auto replies = transcript(wire + status(f, id)); + require_eq(replies.size(), std::size_t{6}); + for (auto i : {1, 2, 3}) { + const auto &record = test::field(replies[i], "result"); + expect_eq(string_field(record, "state"), std::string{"ready"}); + expect(std::holds_alternative(test::field(record, "selected").value)); + } + expect_ready(replies[4], f, "compdb"); +} + +VOID_TEST(ProviderProcess, malformed_unused_external_locator_does_not_shadow_native_metadata) { + Fixture native, external; + native.publish(); + fs::create_directory(external.root / "existing"); + write_bytes(external.compdb, "[]"); + const auto wire = initialization({folder(native)}) + status(native, 9); + for (const auto &spelling : {(external.root / "existing/../compile_commands.json").native(), + external.compdb.native() + "/"}) { + for (const auto *provider : {"auto", "vbs", "compdb"}) { + const auto replies = transcript(wire, {"--workspace-root", native.root.native(), + "--provider", provider, "--compdb", spelling}); + require_eq(replies.size(), std::size_t{3}); + if (std::string_view{provider} == "compdb") { + const auto &record = test::field(replies[1], "result"); + expect_eq(string_field(record, "state"), std::string{"degraded"}); + expect_eq(string_field(record, "provider"), std::string{"compdb"}); + } else { + expect_ready(replies[1], native, "vbs"); + } + } + } +} diff --git a/tests/Registration.cmake b/tests/Registration.cmake deleted file mode 100644 index 2ffd9f6..0000000 --- a/tests/Registration.cmake +++ /dev/null @@ -1,32 +0,0 @@ -cmake_minimum_required(VERSION 4.0) - -foreach(suite IN ITEMS UNIT CAPABILITIES PROCESS) - execute_process(COMMAND "${${suite}}" --list --no-color - RESULT_VARIABLE code OUTPUT_VARIABLE out ERROR_VARIABLE err TIMEOUT 5) - if(NOT "${code}" STREQUAL "0" OR NOT "${err}" STREQUAL "") - message(FATAL_ERROR "${suite} discovery failed: ${code}\n${out}\n${err}") - endif() - string(REPLACE "\n" ";" cases "${out}") - list(FILTER cases EXCLUDE REGEX "^$") - list(LENGTH cases count) - if(suite STREQUAL "UNIT") - set(minimum 22) - elseif(suite STREQUAL "CAPABILITIES") - set(minimum 6) - else() - set(minimum 9) - endif() - if(count LESS minimum) - message(FATAL_ERROR "${suite} registered ${count} tests; expected at least ${minimum}") - endif() - message(STATUS "${suite}: ${count} registered cases") -endforeach() - -# Execute an actual body, observing runner count and exit code rather than relying -# only on a nonempty list from the source scanner. -execute_process(COMMAND "${UNIT}" --no-color --filter "^FramingTests.exact_frame_limits$" - RESULT_VARIABLE code OUTPUT_VARIABLE out ERROR_VARIABLE err TIMEOUT 5) -if(NOT "${code}" STREQUAL "0" OR NOT out MATCHES "1 tests:" OR - NOT out MATCHES "exact_frame_limits") - message(FATAL_ERROR "Named regression did not execute successfully: ${code}\n${out}\n${err}") -endif() diff --git a/tests/TestExecutable.hpp b/tests/TestExecutable.hpp new file mode 100644 index 0000000..b59dc0d --- /dev/null +++ b/tests/TestExecutable.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace test { + +// VBS co-locates a profile's executable and test binaries. The CMake comparison +// build puts tests in a subdirectory and provides an explicit target path. +inline std::filesystem::path server_executable() { +#ifdef VLS_EXECUTABLE + return VLS_EXECUTABLE; +#else + return std::filesystem::read_symlink("/proc/self/exe").parent_path() / "vls"; +#endif +} + +} // namespace test diff --git a/tests/TestSupport.hpp b/tests/TestSupport.hpp index 3ecb057..b57f81e 100644 --- a/tests/TestSupport.hpp +++ b/tests/TestSupport.hpp @@ -59,11 +59,25 @@ inline void expect_error(vls::Server &server, std::string_view request, std::int Void::Testing::expect_eq(error_code(response(server, request)), code); } +inline void expect_sync_capabilities(const vls::Json &result, + std::string_view encoding = "utf-16") { + const auto &capabilities = field(result, "capabilities"); + Void::Testing::expect_eq(std::get(capabilities.value).size(), + std::size_t{3}); + const auto &folders = field(field(capabilities, "workspace"), "workspaceFolders"); + Void::Testing::expect(std::get(field(folders, "supported").value)); + Void::Testing::expect(std::get(field(folders, "changeNotifications").value)); + Void::Testing::expect_eq(std::get(field(capabilities, "positionEncoding").value), + std::string{encoding}); + const auto &sync = field(capabilities, "textDocumentSync"); + Void::Testing::expect(std::get(field(sync, "openClose").value)); + Void::Testing::expect_eq(std::get(field(sync, "change").value), std::int64_t{2}); +} + inline void initialize(vls::Server &server) { const auto result = response(server, R"({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}})"); - Void::Testing::expect( - std::get(field(field(result, "result"), "capabilities").value).empty()); + expect_sync_capabilities(field(result, "result")); } inline constexpr std::string_view initialize_request = diff --git a/tests/corpus/frontend/README.md b/tests/corpus/frontend/README.md new file mode 100644 index 0000000..978e902 --- /dev/null +++ b/tests/corpus/frontend/README.md @@ -0,0 +1,63 @@ +# C++26 frontend reference + +Run the corpus from the repository with GCC 16.2 and the full VoidLibrary +source include directory. The test needs both the public Meta header and its +Detail implementation. + +```sh +dev cpp-gcc -c python3 tests/corpus/frontend/verify-gcc.py \ + --void-include build/bootstrap/_deps/voidlibrary-src/include +``` + +Each invocation creates its own module cache in a temporary directory. The +runner checks both enum helper entry points, the GCC reflection feature macro, +constexpr range expansion, a named module and a reflection splice in its +importer. It verifies the output of the compiled programs and the locations +of two deliberately malformed edits before analyzing the valid importer again. +Retain the fixture line and column positions when reformatting. + +On GCC 16.2, VoidLibrary main `7d7d23e` and libstdc++ dated 20260807, +all 19 checks matched their expected results. Six cases require compiler +diagnostics. Editor queries and the candidate compiler have separate acceptance +criteria in [roadmap 08](../../../docs/roadmap/08-frontend-feasibility.md). + +Probe a locally built candidate using the target triple and standard-library +include directories obtained from the reference GCC driver. The candidate uses +its own compiler resource headers. + +```sh +dev cpp-gcc -c python3 tests/corpus/frontend/probe-clang.py \ + --clang build/frontend-gate/llvm/bin/clang \ + --void-include build/bootstrap/_deps/voidlibrary-src/include +``` + +The JSON report includes driver arguments and each case's exit status and +diagnostics. The process returns nonzero when a tested input fails. On candidate +`562409c7`, six of ten cases passed. The public and internal Void enum helper +checks, the reference meta library and its module importer failed. + +Run the GCC tooling experiment with `dev cpp-gcc -c python3 +tests/corpus/frontend/probe-gcc-tooling.py`. It checks overload and member +bindings in compiler trees, diagnostics after invalid edits, recovery, two +private module generations and nested consteval instantiation. Returned timings +measure individual compiler invocations. The projected edits use temporary +source files and preserve the saved fixture. + +## Live returns on stock GCC + +On x86-64 Linux, run the standalone observation with GCC 16.2.0, its matching +plugin development headers, GMP headers and a Python-enabled GDB. If GMP is in +a separate development prefix, append `--include-dir /path/to/gmp/include`. + +```sh +dev cpp-gcc -c python3 tests/corpus/frontend/verify-stock-gcc-gdb.py +``` + +The probe compiles a small type-description object for GDB. It launches the +installed `cc1plus` on the existing `gcc-live.cpp` fixture with ordinary +compilation flags. The first run observes inner/outer returns of 17/34 and +22/44. Changing the enumerator to 41 produces 41/82 and 46/92 with the same +two assertions. Both members of each pair are read at live return stops in +the same process. This probe depends on the named evaluator remaining +observable in the selected GCC binary. Constraint decisions, splices as +individual events and full editor debugging have separate verification gates. diff --git a/tests/corpus/frontend/enum.cpp b/tests/corpus/frontend/enum.cpp new file mode 100644 index 0000000..3eeae1d --- /dev/null +++ b/tests/corpus/frontend/enum.cpp @@ -0,0 +1,25 @@ +#ifdef PUBLIC_ENTRY +#include +namespace api = Void::Meta; +#else +#include +namespace api = Void::Detail; +#endif +#include + +enum class Source { Idle = 3, Ready = 17 }; +enum class Target { None = 0, Ready = 41 }; + +int main() { + auto name = api::enum_name(Source::Ready); + auto unknown = api::enum_name(static_cast(99)); + auto parsed = api::enum_parse("Ready"); + auto missed = api::enum_parse("ready"); + auto matched = api::enum_cast(Source::Ready); + auto fallback = api::enum_cast(Source::Idle); + std::printf("%.*s %.*s %d %d %d %d\n", int(name.size()), name.data(), + int(unknown.size()), unknown.data(), int(parsed.value_or(Source::Idle)), + int(missed.has_value()), int(matched), int(fallback)); + return !(name == "Ready" && unknown == "?" && parsed == Source::Ready && + !missed && matched == Target::Ready && fallback == Target::None); +} diff --git a/tests/corpus/frontend/expansion-static.cpp b/tests/corpus/frontend/expansion-static.cpp new file mode 100644 index 0000000..b519680 --- /dev/null +++ b/tests/corpus/frontend/expansion-static.cpp @@ -0,0 +1,17 @@ +struct Range { + constexpr const int* begin() const { return values; } + constexpr const int* end() const { return values + 2; } +private: + int values[2]{3, 17}; +}; +consteval int sum() { + static constexpr Range items{}; + int total = 0; +#ifdef INIT_LIST + template for (constexpr int item : {3, 17}) { total += item; } +#else + template for (constexpr int item : items) { total += item; } +#endif + return total; +} +static_assert(sum() == 20); diff --git a/tests/corpus/frontend/gate.cppm b/tests/corpus/frontend/gate.cppm new file mode 100644 index 0000000..af06f2b --- /dev/null +++ b/tests/corpus/frontend/gate.cppm @@ -0,0 +1,9 @@ +module; +#include +export module gate; + +export namespace gate { +enum class State { Idle = 3, Ready = 17 }; +consteval auto ready_info() { return ^^State::Ready; } +template consteval auto materialize() { return [:R:]; } +} diff --git a/tests/corpus/frontend/gcc-evaluation.cpp b/tests/corpus/frontend/gcc-evaluation.cpp new file mode 100644 index 0000000..feeaa08 --- /dev/null +++ b/tests/corpus/frontend/gcc-evaluation.cpp @@ -0,0 +1,16 @@ +#include + +enum class State { Idle = 3, Ready = 17 }; +template concept HasReady = requires { T::Ready; }; + +template consteval int reflected_value() { + constexpr auto ready = ^^T::Ready; + return static_cast([:ready:]); +} + +template consteval int twice() { return 2 * reflected_value(); } + +static_assert(twice() == 34); +#ifdef CHECK_CONSTRAINT_DIAGNOSTIC +constexpr int bad = twice(); +#endif diff --git a/tests/corpus/frontend/gcc-live.cpp b/tests/corpus/frontend/gcc-live.cpp new file mode 100644 index 0000000..010302a --- /dev/null +++ b/tests/corpus/frontend/gcc-live.cpp @@ -0,0 +1,20 @@ +enum class State { Ready = 17 }; + +template concept HasReady = requires { T::Ready; }; + +template consteval int reflected_value(int bias) { + constexpr auto entity = ^^T::Ready; + return static_cast([:entity:]) + bias; +} + +template consteval int twice(int bias) { + return 2 * reflected_value(bias); +} + +// The predicates stay true for both 17 and the edited value 41. They expose +// neither the intermediate result nor its type to the trace verifier. +static_assert(twice(0) > 0); +static_assert(twice(5) > 0); +#ifdef VLS_CHECK_REJECTED_CONSTRAINT +constexpr auto rejected = twice(0); +#endif diff --git a/tests/corpus/frontend/gcc-queries.cpp b/tests/corpus/frontend/gcc-queries.cpp new file mode 100644 index 0000000..d9dd239 --- /dev/null +++ b/tests/corpus/frontend/gcc-queries.cpp @@ -0,0 +1,12 @@ +namespace shapes { +struct Point { + int x; + int y; +}; +constexpr int coordinate(Point p) { return p.x; } +constexpr double coordinate(double value) { return value; } +} // namespace shapes + +int read_x(shapes::Point point) { + return shapes::coordinate(point); +} diff --git a/tests/corpus/frontend/importer.cpp b/tests/corpus/frontend/importer.cpp new file mode 100644 index 0000000..0ec2af0 --- /dev/null +++ b/tests/corpus/frontend/importer.cpp @@ -0,0 +1,8 @@ +#include +import gate; + +static_assert(gate::materialize<^^gate::State::Ready>() == gate::State::Ready); +static_assert([:gate::ready_info():] == gate::State::Ready); +static_assert(std::meta::identifier_of(gate::ready_info()) == "Ready"); + +int main() { return int([:gate::ready_info():]) == 17 ? 0 : 1; } diff --git a/tests/corpus/frontend/invalid-name.cpp b/tests/corpus/frontend/invalid-name.cpp new file mode 100644 index 0000000..49ad230 --- /dev/null +++ b/tests/corpus/frontend/invalid-name.cpp @@ -0,0 +1,8 @@ +#include +import gate; + +static_assert(gate::materialize<^^gate::State::Readi>() == gate::State::Ready); +static_assert([:gate::ready_info():] == gate::State::Ready); +static_assert(std::meta::identifier_of(gate::ready_info()) == "Ready"); + +int main() { return int([:gate::ready_info():]) == 17 ? 0 : 1; } diff --git a/tests/corpus/frontend/invalid-splice.cpp b/tests/corpus/frontend/invalid-splice.cpp new file mode 100644 index 0000000..d768d46 --- /dev/null +++ b/tests/corpus/frontend/invalid-splice.cpp @@ -0,0 +1,8 @@ +#include +import gate; + +static_assert(gate::materialize<^^gate::State::Ready>() == gate::State::Ready); +static_assert([:gate::ready_info()] == gate::State::Ready); +static_assert(std::meta::identifier_of(gate::ready_info()) == "Ready"); + +int main() { return int([:gate::ready_info():]) == 17 ? 0 : 1; } diff --git a/tests/corpus/frontend/library.cpp b/tests/corpus/frontend/library.cpp new file mode 100644 index 0000000..a0182f0 --- /dev/null +++ b/tests/corpus/frontend/library.cpp @@ -0,0 +1,11 @@ +#include +#ifndef __GLIBCXX__ +#error expected libstdc++ +#elif !defined(__cpp_lib_reflection) || __cpp_lib_reflection < 202603L +#error GCC 16.2 reflection declarations are inactive +#else +enum class State { Idle = 3, Ready = 17 }; +using Items = decltype(std::define_static_array(std::meta::enumerators_of(^^State))); +static_assert(std::is_same_v>); +static_assert(std::meta::identifier_of(std::meta::enumerators_of(^^State)[1]) == "Ready"); +#endif diff --git a/tests/corpus/frontend/probe-clang.py b/tests/corpus/frontend/probe-clang.py new file mode 100644 index 0000000..015b8c4 --- /dev/null +++ b/tests/corpus/frontend/probe-clang.py @@ -0,0 +1,78 @@ +"""Probe a candidate Clang with the reference GCC's C++ and platform headers.""" + +import argparse +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +FIXTURES = Path(__file__).resolve().parent + + +def run(argv, *, source="", cwd=None, checked=True): + return subprocess.run( + argv, input=source, text=True, capture_output=True, check=checked, + timeout=60, cwd=cwd, env={**os.environ, "LC_ALL": "C"}, + ) + + +def reference_flags(clang, gcc): + triple = run([gcc, "-dumpmachine"]).stdout.strip() + search = run([gcc, "-E", "-x", "c++", "-v", "-"]).stderr + start = "#include <...> search starts here:" + paths = search.split(start, 1)[1].split("End of search list.", 1)[0].splitlines() + gcc_builtin = Path(run([gcc, "-print-file-name=include"]).stdout.strip()).resolve() + resource = Path(run([clang, "-print-resource-dir"]).stdout.strip()) / "include" + flags = [f"--target={triple}", "-nostdinc"] + for raw in paths: + if raw.strip(): + path = Path(raw.strip()).resolve(strict=True) + flags.extend(["-isystem", str(resource if path == gcc_builtin else path)]) + return flags + + +def probe(clang, gcc, void_include, work): + report = { + "clang": run([clang, "--version"]).stdout.splitlines()[0], + "gcc": run([gcc, "--version"]).stdout.splitlines()[0], + "cases": {}, + } + base = [str(clang), "--driver-mode=g++", "-std=c++26", "-freflection", + "-fexpansion-statements", "-ferror-limit=4", *reference_flags(clang, gcc)] + report["driver"] = base + + def check(name, args, source=""): + result = run([*base, *args], source=source, cwd=work, checked=False) + report["cases"][name] = {"exit": result.returncode, "stderr": result.stderr[:6000]} + return result.returncode == 0 + + check("reference cstddef", ["-fsyntax-only", "-x", "c++", "-"], + "#include \n#ifndef __GLIBCXX__\n#error expected libstdc++\n#endif\n") + check("language reflection and splice", ["-fsyntax-only", "-x", "c++", "-"], + "enum class E { x }; static_assert([:^^E::x:] == E::x);\n") + check("constexpr range expansion", ["-fsyntax-only", FIXTURES / "expansion-static.cpp"]) + if check("plain module interface", ["--precompile", "-x", "c++-module", "-", "-o", "control.pcm"], + "export module control; export constexpr int answer = 42;\n"): + check("plain module importer", ["-fmodule-file=control=control.pcm", "-fsyntax-only", "-x", "c++", "-"], + "import control; static_assert(answer == 42);\n") + check("reference meta library", ["-fsyntax-only", FIXTURES / "library.cpp"]) + for name, flags in (("Void detail enum", []), ("Void public enum", ["-DPUBLIC_ENTRY"])): + check(name, [*flags, "-I", void_include, "-fsyntax-only", FIXTURES / "enum.cpp"]) + if check("Void reflection module", ["--precompile", FIXTURES / "gate.cppm", "-o", "gate.pcm"]): + check("Void module importer", ["-fmodule-file=gate=gate.pcm", "-fsyntax-only", FIXTURES / "importer.cpp"]) + return report + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--clang", type=Path, required=True) + parser.add_argument("--gcc", default="g++") + parser.add_argument("--void-include", type=Path, required=True) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="vls-clang-corpus-") as scratch: + result = probe(args.clang.resolve(strict=True), args.gcc, + args.void_include.resolve(strict=True), Path(scratch)) + print(json.dumps(result, indent=2)) + raise SystemExit(int(any(record["exit"] for record in result["cases"].values()))) diff --git a/tests/corpus/frontend/probe-gcc-tooling.py b/tests/corpus/frontend/probe-gcc-tooling.py new file mode 100644 index 0000000..05c971d --- /dev/null +++ b/tests/corpus/frontend/probe-gcc-tooling.py @@ -0,0 +1,156 @@ +"""Exercise GCC 16's observable query, recovery, module and metaprogram data.""" + +import argparse +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +import time + + +FIXTURES = Path(__file__).resolve().parent + + +def run(argv, work, expected=0): + start = time.monotonic() + result = subprocess.run(argv, cwd=work, env={**os.environ, "LC_ALL": "C"}, + capture_output=True, text=True, timeout=60) + if result.returncode != expected: + raise RuntimeError(f"{argv}: expected {expected}, got {result.returncode}\n{result.stderr}") + return result, round((time.monotonic() - start) * 1000, 2) + + +def require(value, reason): + if not value: + raise ValueError(reason) + + +def fixture_tree(path): + # This fixture has a single invocation and a single field access. Its node + # numbers and declaration ordering may change independently of its bindings. + nodes = {} + for match in re.finditer(r"^@(\d+)\s+(\w+)\s+(.*?)(?=^@\d+|\Z)", + path.read_text(), re.MULTILINE | re.DOTALL): + nodes[match[1]] = (match[2], match[3]) + return nodes + + +def edge(nodes, node, key, expected_kind=None): + target = re.search(r"(?= 1, "missing source column") + return {"message": entry["message"]["text"], "region": region, + "related_locations": len(entry.get("relatedLocations", []))} + raise ValueError(f"missing {source_name}:{line} diagnostic containing {needle}") + + +def check_modules(flags, work, value): + # A content generation gets an isolated GCC module cache. Compile an + # importer against the new interface and a control expecting the old value. + work.mkdir() + provider = (FIXTURES / "gate.cppm").read_text() + require(provider.count("Ready = 17") == 1, "expected one serialized enum value") + (work / "gate.cppm").write_text(provider.replace("Ready = 17", f"Ready = {value}")) + importer = (FIXTURES / "importer.cpp").read_text() + importer += f"\nstatic_assert(int([:gate::ready_info():]) == {value});\n" + (work / "importer.cpp").write_text(importer) + _, compile_ms = run([*flags, "-fmodules", "-x", "c++", "-c", "gate.cppm", "-o", "gate.o"], work) + _, import_ms = run([*flags, "-fmodules", "-fsyntax-only", "importer.cpp"], work) + other = 41 if value == 17 else 17 + (work / "control.cpp").write_text(importer + f"static_assert(int([:gate::ready_info():]) == {other});\n") + failed, _ = run([*flags, "-fmodules", "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", + "control.cpp"], work, expected=1) + diagnostic(failed.stderr, "control.cpp", len((work / "control.cpp").read_text().splitlines()), + "static assertion failed") + return {"case": f"private module generation {value}", "imported_value": value, + "interface_ms": compile_ms, "import_ms": import_ms} + + +def probe(compiler, work): + version, _ = run([compiler, "-dumpfullversion"], work) + require(version.stdout.startswith("16."), f"expected GCC 16, got {version.stdout}") + flags = [compiler, "-std=c++26", "-freflection"] + saved = (FIXTURES / "gcc-queries.cpp").read_text() + projected = saved.replace("shapes::Point point)", "shapes::Point point, double weight)").replace( + "coordinate(point)", "coordinate(weight)") + cases = [check_query(flags, work, saved, "saved overload", 6, "int"), + check_query(flags, work, projected, "projected edit", 7, "double")] + (work / "query.cpp").write_text(projected.replace("coordinate(weight)", "missing(weight)")) + failed, _ = run([*flags, "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", "query.cpp"], + work, expected=1) + cases.append({"case": "malformed edit", **diagnostic(failed.stderr, "query.cpp", 11, "missing")}) + cases.append(check_query(flags, work, saved, "recovered overload", 6, "int")) + for value in (17, 41): + cases.append(check_modules(flags, work / f"module-{value}", value)) + source = FIXTURES / "gcc-evaluation.cpp" + trace = work / "template.txt" + run([*flags, f"-fdump-lang-tinst={trace}", "-fsyntax-only", source], work) + lines = trace.read_text().splitlines() + outer = next(i for i, line in enumerate(lines) if re.match(r"I consteval int twice\(\).*State", line)) + require(any(re.match(r" I consteval int reflected_value\(\).*State", line) + for line in lines[outer + 1:]), "missing nested consteval instantiation") + cases.append({"case": "template instantiation dump", "outer": "twice", + "inner": "reflected_value"}) + failed, _ = run([*flags, "-DCHECK_CONSTRAINT_DIAGNOSTIC", "-fconcepts-diagnostics-depth=3", + "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", source], work, expected=1) + constraint = diagnostic(failed.stderr, source.name, 11, "reflected_value") + require(constraint["related_locations"] > 0, "constraint failure has no related source locations") + cases.append({"case": "constraint rejection", **constraint}) + require((FIXTURES / "gcc-queries.cpp").read_text() == saved, "saved input changed") + return {"gcc": version.stdout.strip(), "cases": cases} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cxx", default="g++") + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="vls-gcc-tooling-") as temp: + print(json.dumps(probe(args.cxx, Path(temp)), indent=2)) diff --git a/tests/corpus/frontend/range-static.cpp b/tests/corpus/frontend/range-static.cpp new file mode 100644 index 0000000..dc5f6c2 --- /dev/null +++ b/tests/corpus/frontend/range-static.cpp @@ -0,0 +1,10 @@ +#include + +enum class State { Idle = 3, Ready = 17 }; +consteval int sum() { + static constexpr auto items = std::define_static_array(std::meta::enumerators_of(^^State)); + int total = 0; + template for (constexpr auto item : items) { total += int([:item:]); } + return total; +} +static_assert(sum() == 20); diff --git a/tests/corpus/frontend/range.cpp b/tests/corpus/frontend/range.cpp new file mode 100644 index 0000000..f8e2b30 --- /dev/null +++ b/tests/corpus/frontend/range.cpp @@ -0,0 +1,10 @@ +#include + +enum class State { Idle = 3, Ready = 17 }; +consteval int sum() { + constexpr auto items = std::define_static_array(std::meta::enumerators_of(^^State)); + int total = 0; + template for (constexpr auto item : items) { total += int([:item:]); } + return total; +} +static_assert(sum() == 20); diff --git a/tests/corpus/frontend/verify-gcc-events.py b/tests/corpus/frontend/verify-gcc-events.py new file mode 100644 index 0000000..104a669 --- /dev/null +++ b/tests/corpus/frontend/verify-gcc-events.py @@ -0,0 +1,550 @@ +#!/usr/bin/env python3 +"""Exercise the private GCC evaluator on the real gcc-live.cpp translation unit.""" +import argparse +from contextlib import ExitStack +import json +import os +from pathlib import Path +import re +import secrets +import select +import selectors +import signal +import subprocess +import sys +import tempfile +import time + +BACKEND = "gcc-16.2.0/vls-eval-1" +KINDS = {"hello", "enter", "body", "cached", "value", "stopped", "resumed", + "leave", "terminal", "frontendEnd"} +TRACE_LIMIT = 1024 * 1024 +FRAME_LIMIT = 64 * 1024 +DEADLINE = 10 + +# Relocate both inherited endpoints before touching 3 or 4. exec preserves the +# PID; raw stdin/stdout and diagnostics are independent of the two probe pipes. +LAUNCH = """ +import fcntl, os, sys +original = [int(fd) for fd in sys.argv[1:3]] +high = [fcntl.fcntl(fd, fcntl.F_DUPFD_CLOEXEC, 5) for fd in original] +for fd, target in zip(high, (3, 4)): + os.dup2(fd, target, inheritable=True) +for fd in original: + if fd > 4: + os.close(fd) +os.execv(sys.argv[3], sys.argv[3:]) +""" + + +def check(condition, message): + if not condition: + raise AssertionError(message) + + +def unique_keys(pairs): + result = {} + for key, value in pairs: + check(key not in result, f"duplicate JSON key {key!r}") + result[key] = value + return result + + +def reject_number(value): + raise ValueError(f"non-JSON number {value}") + + +def integer(value): + check(set(value) == {"kind", "precision", "signed", "bitsHex"}, + f"malformed integer {value}") + width, signed, bits = value["precision"], value["signed"], value["bitsHex"] + check(type(width) is int and 1 <= width <= 64 and type(signed) is bool, + f"invalid integer type {value}") + check(isinstance(bits, str) and len(bits) == (width + 3) // 4 + and re.fullmatch("[0-9a-f]+", bits), f"invalid integer encoding {value}") + raw = int(bits, 16) + check(raw < 1 << width, f"excess bits {value}") + return raw - (1 << width) if signed and raw & (1 << (width - 1)) else raw + + +class Invocation: + """Own and reap one private cc1plus process, with bounded multiplexed reads.""" + + def __init__(self, binary, source, flags, nonce=None, invalid_pipe=False): + self.nonce = nonce if nonce is not None else secrets.token_hex(16) + self.events = [] + self.pending = bytearray() + self.trace_bytes = 0 + self.outputs = {"stdout": bytearray(), "stderr": bytearray()} + self.mux = selectors.DefaultSelector() + self.deadline = time.monotonic() + DEADLINE + self.control = None + self.process = None + self.owned = ExitStack() + self.owned.callback(self.mux.close) + try: + with ExitStack() as child: + control_read, self.control = os.pipe() + child.callback(os.close, control_read) + self.owned.callback(self.close_control) + event_read, event_write = os.pipe() + self.owned.callback(os.close, event_read) + child.callback(os.close, event_write) + if invalid_pipe: + event_write = os.open(os.devnull, os.O_WRONLY) + child.callback(os.close, event_write) + args = [sys.executable, "-I", "-c", LAUNCH, str(control_read), + str(event_write), str(binary), "-quiet", "-std=c++26", + "-freflection", "-fsyntax-only", "-nostdinc", *flags, + source.name, "-o", os.devnull] + self.process = subprocess.Popen( + args, cwd=source.parent, + env={"LC_ALL": "C", "VLS_GCC_NONCE": self.nonce}, + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + pass_fds=(control_read, event_write), start_new_session=True) + self.owned.callback(self.process.stdout.close) + self.owned.callback(self.process.stderr.close) + os.set_blocking(self.control, False) + for stream, channel in ((event_read, "trace"), (self.process.stdout, "stdout"), + (self.process.stderr, "stderr")): + self.mux.register(stream, selectors.EVENT_READ, channel) + except BaseException: + self.close() + raise + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + + def close_control(self): + if self.control is not None: + os.close(self.control) + self.control = None + + def close(self): + try: + if self.process is not None and self.process.poll() is None: + try: + os.killpg(self.process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + self.process.wait(timeout=2) + finally: + self.owned.close() + + def remaining(self): + seconds = self.deadline - time.monotonic() + check(seconds > 0, f"cc1plus timeout after {len(self.events)} events") + return seconds + + def trace(self, data): + self.trace_bytes += len(data) + check(self.trace_bytes <= TRACE_LIMIT, "trace too large") + self.pending.extend(data) + while (end := self.pending.find(b"\n")) >= 0: + check(end + 1 <= FRAME_LIMIT, "frame too large") + event = json.loads(bytes(self.pending[:end]).decode("utf-8", errors="strict"), + object_pairs_hook=unique_keys, parse_constant=reject_number) + del self.pending[:end + 1] + index = len(self.events) + check(isinstance(event, dict) and type(event.get("v")) is int and event["v"] == 1 + and event.get("nonce") == self.nonce and type(event.get("seq")) is int + and event["seq"] == index and index < 4096 and event.get("kind") in KINDS, + f"invalid envelope at {index}: {event}") + if index == 0: + check(event["kind"] == "hello" and event.get("backend") == BACKEND + and event.get("pid") == self.process.pid and set(event["kinds"]) == KINDS + and {"integralReturn", "cooperativeStep"} <= set(event["capabilities"]), + f"unexpected handshake {event}") + self.events.append(event) + check(len(self.pending) < FRAME_LIMIT, "oversized unfinished frame") + + def pump(self, timeout): + for key, _ in self.mux.select(timeout=min(timeout, self.remaining())): + data = os.read(key.fd, 16384) + if not data: + self.mux.unregister(key.fileobj) + continue + if key.data == "trace": + self.trace(data) + else: + output = self.outputs[key.data] + output.extend(data) + check(len(output) <= 256 * 1024, f"{key.data} exceeded its byte limit") + + def next_stop(self, after=-1): + while True: + for event in self.events[after + 1:]: + if event["kind"] == "stopped": + return event + check(self.mux.get_map(), f"missing stopped event: {self.outputs['stderr'][:500]!r}") + self.pump(self.remaining()) + + def held(self, stop): + end = time.monotonic() + 0.1 + while time.monotonic() < end: + self.pump(max(0, end - time.monotonic())) + check(self.process.poll() is None and os.getpgid(self.process.pid) == self.process.pid, + "compiler left the held stop") + check(self.events[-1] == stop and not self.pending, "compiler emitted data past the stop") + + def send(self, data): + while data: + _, writable, _ = select.select([], [self.control], [], self.remaining()) + check(writable, "timeout sending control") + try: + size = os.write(self.control, data) + except BlockingIOError: + continue + check(size > 0, "short control write") + data = data[size:] + + def command(self, stop, action): + return f"{self.nonce} {stop['seq']} {action}\n".encode("ascii") + + def wait(self, code): + while self.mux.get_map(): + self.pump(self.remaining()) + result = self.process.wait(timeout=self.remaining()) + check(not self.pending, "truncated last record") + check(not self.outputs["stdout"], f"unexpected stdout {self.outputs['stdout'][:200]!r}") + check(result == code, f"exit {result}, expected {code}: {self.outputs['stderr'][:500]!r}") + return bytes(self.outputs["stderr"]) + + +def frames(events, terminal="frontendEnd"): + """Check the full call/stop grammar and index each observed frame's evidence.""" + check(events and events[0]["kind"] == "hello" and events[-1]["kind"] == terminal, + f"missing handshake or expected {terminal}") + calls, stack = {}, [] + stopped = None + for i, event in enumerate(events[1:], 1): + kind = event["kind"] + if stopped is not None: + check(kind in ("resumed", "terminal") and event.get("stop") == stopped["seq"], + "unacknowledged stop") + if kind in ("terminal", "frontendEnd"): + check(i == len(events) - 1, "records after termination") + if kind == "frontendEnd": + check(not stack and stopped is None, "unfinished calls at frontendEnd") + continue + frame = event.get("frame") + parent = event.get("parent") + check(type(frame) is int and frame > 0 and "parent" in event + and (parent is None or type(parent) is int), f"invalid call identity {event}") + if kind == "enter": + check(frame not in calls and parent == (stack[-1] if stack else None), + "wrong call parent or reused frame") + stack.append(frame) + calls[frame] = {"enter": event} + continue + check(stack and frame == stack[-1] and calls[frame]["enter"]["parent"] == parent, + "event for inactive frame") + call = calls[frame] + check(kind not in call, f"duplicate {kind} in frame {frame}") + call[kind] = event + if kind == "body": + check("cached" not in call, "body for cache hit") + elif kind == "cached": + check("body" not in call and "value" not in call, "cache hit with observed body") + elif kind == "value": + check("body" in call, "value outside body") + value = event["value"] + if value["kind"] == "integer": + integer(value) + else: + check(value == {"kind": "unavailable", "reason": "unsupportedScalar"}, + f"invalid unavailable value {value}") + elif kind == "stopped": + prev = events[i - 1] + check(prev["kind"] == "value" and prev["frame"] == frame + and prev["value"]["kind"] == "integer", "stop without an actual integer") + stopped = event + elif kind == "resumed": + check(stopped is not None and event["action"] in ("step", "continue"), + "unmatched resume") + stopped = None + elif kind == "leave": + check(event["outcome"] in {"returned", "failed", "overflow", "throw", "jump", + "void", "constructor"}, f"unexpected outcome {event}") + stack.pop() + else: + raise AssertionError(f"unexpected {kind}") + return calls + + +def witness(calls, ready): + pairs = [] + for frame, outer in calls.items(): + if outer["enter"]["name"] != "twice" or "value" not in outer: + continue + children = [c for c in calls.values() if c["enter"]["parent"] == frame + and c["enter"]["name"] == "reflected_value" and "value" in c] + check(len(children) == 1, f"expected inner reflected_value for frame {frame}") + inner = children[0] + check(outer["body"]["seq"] < inner["enter"]["seq"] < inner["body"]["seq"] + < inner["value"]["seq"] < inner["leave"]["seq"] < outer["value"]["seq"] + < outer["leave"]["seq"], "observed values outside their dynamic bodies") + for call in (inner, outer): + check(call["leave"]["outcome"] == "returned", "return failed after capture") + check(call["value"]["value"]["signed"] and call["value"]["value"]["precision"] == 32, + "fixture did not return int") + pairs.append((integer(inner["value"]["value"]), integer(outer["value"]["value"]))) + expected = [(ready, 2 * ready), (ready + 5, 2 * (ready + 5))] + check(pairs == expected, f"observed {pairs}, expected {expected}") + return pairs + + +OBSERVE = ["-fvls-observe"] +STEP = [*OBSERVE, "-fvls-step"] + + +def completed(binary, source, flags, code=0, **kwargs): + with Invocation(binary, source, flags, **kwargs) as run: + diagnostics = run.wait(code) + return run.events, diagnostics + + +def values_and_parity(binary, source, original): + for ready in (17, 41): + edited = original.replace("Ready = 17", f"Ready = {ready}") + check(edited.count(">(0) > 0") == 1 and edited.count(">(5) > 0") == 1, + "fixture predicates changed") + source.write_text(edited, encoding="utf-8") + disabled, reference = completed(binary, source, []) + observed, diagnostics = completed(binary, source, OBSERVE) + check(not disabled and reference == diagnostics == b"", "disabled/on parity failed") + calls = frames(observed) + pairs = witness(calls, ready) + for call in calls.values(): + enter = call["enter"] + if enter["name"] in ("reflected_value", "twice"): + check(enter.get("sourceKind") == "logicalDeclaration" + and enter["source"] == source.name and enter["byteColumn"] > 0 + and enter["line"] in (5, 10), f"unexpected declaration location {enter}") + print(f"Ready={ready} real integral returns at bias 0 and 5: {pairs}") + + +def control_cases(binary, source): + with Invocation(binary, source, STEP) as run: + inner = run.next_stop() + frames_seen = {e["frame"]: e for e in run.events if e["kind"] == "enter"} + value = run.events[inner["seq"] - 1] + check(frames_seen[inner["frame"]]["name"] == "reflected_value" + and frames_seen[inner["parent"]]["name"] == "twice" + and value["frame"] == inner["frame"] and integer(value["value"]) == 17, + "first stop outside the real inner return") + run.held(inner) + # Same shape but guaranteed different nonce; old and future sequences, + # an unrecognized action, and a NUL suffix must also leave the child held. + other = ("0" if run.nonce[0] != "0" else "1") + run.nonce[1:] + run.send(f"{other} {inner['seq']} step\n".encode()) + run.send(run.command({"seq": inner["seq"] - 1}, "continue")) + run.send(run.command({"seq": inner["seq"] + 1}, "cancel")) + run.send(run.command(inner, "step\0garbage")) + run.held(inner) + command = run.command(inner, "step") + run.send(command[:-1]) + run.held(inner) + run.send(command[-1:]) + outer = run.next_stop(after=inner["seq"]) + check(outer["frame"] == inner["parent"] + and integer(run.events[outer["seq"] - 1]["value"]) == 34, + "step did not reach the outer return") + run.send(run.command(inner, "continue")) + run.held(outer) + run.send(run.command(outer, "continue")) + check(not run.wait(0), "unexpected step diagnostics") + witness(frames(run.events), 17) + acks = [(e["stop"], e["action"]) for e in run.events if e["kind"] == "resumed"] + check(acks == [(inner["seq"], "step"), (outer["seq"], "continue")], + f"wrong control acknowledgements {acks}") + print(f"PID {run.process.pid} held at inner 17, stepped to outer 34, continued and reaped") + + for action, reason, code in (("cancel", "cancelled", 125), ("EOF", "controlEOF", 126), + ("oversize", "controlLimit", 126)): + with Invocation(binary, source, STEP) as run: + stop = run.next_stop() + check(integer(run.events[stop["seq"] - 1]["value"]) == 17, "wrong initial stop") + run.held(stop) + if action == "EOF": + run.close_control() + elif action == "oversize": + run.send(b"x" * 4097) + else: + run.send(run.command(stop, action)) + run.wait(code) + calls = frames(run.events, "terminal") + check(run.events[-1]["reason"] == reason and "value" not in calls[stop["parent"]], + "control loss or cancellation allowed outer evaluation") + print(f"{action} at inner stop: {reason}, exit {code}, reaped PID {run.process.pid}") + + +SCALARS = """ +consteval signed char narrow(int n) { return static_cast(-n); } +consteval unsigned long long high(unsigned n) { return (1ULL << 63) + n; } +consteval long long negative(long long n) { return -n; } +consteval bool flag(int n) { return n != 0; } +consteval __int128 wide(int n) { return static_cast<__int128>(n) << 64; } +consteval double floating(int n) { return static_cast(n); } +consteval int reuse(int n) { return n + 1; } +consteval int repeat(int n) { return reuse(n) + reuse(n); } +static_assert(narrow(3) < 0 && high(5) > 0 && flag(7)); +static_assert(negative(23) < 0 && wide(7) > 0 && floating(3) > 0); +static_assert(repeat(11) > 0); +""" + +FAILURES = """ +consteval int may_throw(int n) { + if (n) throw n; + return n; +} +consteval int recover(int n) { + try { return may_throw(n); } catch (int caught) { return caught * 2; } +} +static_assert(recover(7) > 0); +struct Piece { int x; constexpr Piece(int n): x(n) {} }; +constexpr void bump(Piece& p) { ++p.x; } +consteval int worked(int n) { Piece p(n); bump(p); return p.x; } +static_assert(worked(18) > 0); +""" + +BAD_CLEANUP = """ +struct Gone { int x; }; +consteval int provisional(Gone g, Gone*& p) { p = &g; g.~Gone(); return 9; } +consteval int caller(int n) { Gone* p; return provisional(Gone{n}, p); } +static_assert(caller(5) > 0); +""" + +OVERFLOW = """ +consteval int over(int n) { return n + 1; } +static_assert(over(__INT_MAX__) > 0); +""" + +LIMIT = """ +consteval int one(int n) { return n + 1; } +consteval int many(int count) { + int sum = 0; + for (int i = 0; i < count; ++i) sum += one(i); + return sum; +} +static_assert(many(1600) > 0); +""" + + +def scalar_cases(binary, source, original): + source.write_text(original + SCALARS + FAILURES, encoding="utf-8") + events, diagnostics = completed(binary, source, OBSERVE) + check(not diagnostics, f"unexpected scalar diagnostics {diagnostics[:400]!r}") + calls = frames(events) + by_name = {} + for call in calls.values(): + by_name.setdefault(call["enter"]["name"], []).append(call) + + def snapshot(name): + values = [c["value"]["value"] for c in by_name[name] if "value" in c + and c["leave"]["outcome"] == "returned"] + check(len(values) == 1, f"expected one scalar result for {name}, got {values}") + return values[0] + + for name, width, signed, bits in ( + ("narrow", 8, True, "fd"), ("high", 64, False, "8000000000000005"), + ("negative", 64, True, "ffffffffffffffe9"), ("flag", 1, False, "1")): + value = snapshot(name) + check((value["precision"], value["signed"], value["bitsHex"]) == (width, signed, bits), + f"{name}: wrong bits or type {value}") + for name in ("wide", "floating"): + check(snapshot(name)["kind"] == "unavailable", f"{name}: unsupported scalar reported") + hits = [c for c in by_name["reuse"] if "cached" in c] + check(hits and all("body" not in c and "value" not in c for c in hits), + "reused evaluator result had no distinct cache-hit witness") + check(all(not any(x["enter"]["parent"] == hit["enter"]["frame"] for x in calls.values()) + for hit in hits), "cache hit fabricated children") + thrown = [c for c in by_name["may_throw"] if c["leave"]["outcome"] == "throw"] + check(thrown and all("value" not in c for c in thrown), "throw reported a normal return") + check(integer(snapshot("recover")) == 14, "caught exception lost its caller's return") + constructors = [c for c in calls.values() if c["leave"]["outcome"] == "constructor"] + check(constructors and all("value" not in c for c in constructors) + and all(c["leave"]["outcome"] == "void" and "value" not in c for c in by_name["bump"]) + and integer(snapshot("worked")) == 19, "misclassified void or constructor") + print("Verified integer widths and bits, unsupported scalars, cache, throw, void and constructor") + + +def failure_parity(binary, source, original): + source.write_text(original, encoding="utf-8") + reject = ["-DVLS_CHECK_REJECTED_CONSTRAINT"] + disabled, reference = completed(binary, source, reject, 1) + events, diagnostics = completed(binary, source, [*OBSERVE, *reject], 1) + check(not disabled and reference == diagnostics and b"constraints not satisfied" in diagnostics, + "constraint diagnostic changed in the observed compiler") + frames(events) + for tail, name, outcome in ((BAD_CLEANUP, "provisional", "failed"), + (OVERFLOW, "over", "overflow")): + source.write_text(original + tail, encoding="utf-8") + disabled, reference = completed(binary, source, [], 1) + events, diagnostics = completed(binary, source, OBSERVE, 1) + check(not disabled and reference and reference == diagnostics, f"{name} diagnostic changed") + attempts = [c for c in frames(events).values() if c["enter"]["name"] == name] + check(attempts and all(c["leave"]["outcome"] == outcome for c in attempts), + f"{name} lost its final outcome") + if name == "provisional": + check(all(integer(c["value"]["value"]) == 9 for c in attempts) + and b"outside its lifetime" in reference, "missing provisional pre-cleanup value") + else: + check(all("value" not in c for c in attempts), "fabricated integer on overflow") + source.write_text(original, encoding="utf-8") + for flags, nonce, invalid_pipe in ((OBSERVE, "a" * 31, False), + (OBSERVE, "A" * 32, False), + (OBSERVE, None, True), + (["-fvls-step"], None, False)): + events, diagnostics = completed(binary, source, flags, 1, + nonce=nonce, invalid_pipe=invalid_pipe) + check(not events and b"invalid private evaluator observer setup" in diagnostics, + "invalid setup did not fail before emitting events") + print("Matched constraint, cleanup and overflow diagnostics; provisional 9 left as failed") + print("Four invalid observer setups rejected before handshake") + + +def wire_limits(binary, directory, original): + for name, expected in (('quote"slash\\.cpp', 'quote"slash\\.cpp'), ("ctrl\x1f.cpp", None), + (os.fsdecode(b"byte\xff.cpp"), None)): + source = directory / name + source.write_text(original, encoding="utf-8") + events, diagnostics = completed(binary, source, OBSERVE) + check(not diagnostics, "unexpected diagnostics for source name") + calls = frames(events) + witness(calls, 17) + check(all("source" in c["enter"] and c["enter"]["source"] == expected + for c in calls.values()), "unescaped or incorrectly reconstructed source name") + source = directory / "many.cpp" + source.write_text(original + LIMIT, encoding="utf-8") + events, _ = completed(binary, source, OBSERVE, 126) + frames(events, "terminal") + check(len(events) == 4096 and events[-1]["reason"] == "truncated", "invalid quota result") + print(f"Strict JSON survived special source names; event quota closed at {len(events)} records") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cc1plus", type=Path, required=True, help="absolute private cc1plus path") + binary = parser.parse_args().cc1plus + check(binary.is_absolute() and binary.is_file() and os.access(binary, os.X_OK), + "supply the absolute path to the patched private cc1plus") + original = Path(__file__).with_name("gcc-live.cpp").read_text(encoding="utf-8") + check(original.count("Ready = 17") == 1, "fixture no longer has its controlled edit") + with tempfile.TemporaryDirectory(prefix="vls-gcc-events-") as work: + directory = Path(work) + source = directory / "live.cpp" + values_and_parity(binary, source, original) + source.write_text(original, encoding="utf-8") + control_cases(binary, source) + scalar_cases(binary, source, original) + failure_parity(binary, source, original) + wire_limits(binary, directory, original) + print(f"{BACKEND} direct evaluator checks passed") + + +if __name__ == "__main__": + main() diff --git a/tests/corpus/frontend/verify-gcc-ide.py b/tests/corpus/frontend/verify-gcc-ide.py new file mode 100644 index 0000000..6a8ca69 --- /dev/null +++ b/tests/corpus/frontend/verify-gcc-ide.py @@ -0,0 +1,292 @@ +#!/usr/bin/env python3 +"""Verify private GCC 16.2 IDE observations against sealed primary-file snapshots.""" + +import argparse +from contextlib import ExitStack +from dataclasses import dataclass +import fcntl +import hashlib +import json +import os +from pathlib import Path +import re +import runpy +import secrets +import selectors +import signal +import subprocess +import sys +import tempfile +import time + + +HERE = Path(__file__).resolve().parent +WIRE = runpy.run_path(str(HERE / "verify-gcc-events.py")) +check = WIRE["check"] +KINDS = {"hello", "occurrence", "ideCoverage", "frontendEnd", "terminal"} +IDE = ("-fvls-observe", "-fvls-ide") +TRACE_LIMIT = 1024 * 1024 +SIDE_LIMIT = 256 * 1024 + + +def strict_json(data): + return json.loads(data.decode("utf-8", errors="strict"), + object_pairs_hook=WIRE["unique_keys"], parse_constant=WIRE["reject_number"]) + + +def sealed_file(owned, data): + check(len(data) <= 256 * 1024, "oversized primary snapshot") + # Keep the immutable source open across the fd 3/4 launcher shuffle. + initial = os.memfd_create("vls-query.cpp", os.MFD_CLOEXEC | os.MFD_ALLOW_SEALING) + try: + fd = fcntl.fcntl(initial, fcntl.F_DUPFD_CLOEXEC, 5) + finally: + os.close(initial) + owned.callback(os.close, fd) + with os.fdopen(os.dup(fd), "wb") as output: + output.write(data) + seals = fcntl.F_SEAL_WRITE | fcntl.F_SEAL_GROW | fcntl.F_SEAL_SHRINK | fcntl.F_SEAL_SEAL + fcntl.fcntl(fd, fcntl.F_ADD_SEALS, seals) + check(fcntl.fcntl(fd, fcntl.F_GET_SEALS) & seals == seals, "source seal failed") + return fd + + +@dataclass +class Result: + source: bytes + snapshot: str + nonce: str + pid: int + events: list + stderr: bytes + + +def run(binary, source, flags=IDE, expected=0, valid_digest=True): + data = source.encode("utf-8") + digest = hashlib.sha256(data).hexdigest() + nonce = secrets.token_hex(16) + env = {"LC_ALL": "C", "VLS_GCC_NONCE": nonce, + "VLS_GCC_SNAPSHOT": digest if valid_digest else digest[:-1]} + deadline = time.monotonic() + 10 + + def remaining(): + left = deadline - time.monotonic() + check(left > 0, "cc1plus deadline expired") + return left + + with tempfile.TemporaryDirectory(prefix="vls-gcc-ide-") as work, ExitStack() as owned: + snapshot_fd = sealed_file(owned, data) + (Path(work) / "query.cpp").symlink_to(f"/proc/self/fd/{snapshot_fd}") + with ExitStack() as child: + control_read, control_write = os.pipe() + child.callback(os.close, control_read) + owned.callback(os.close, control_write) + event_read, event_write = os.pipe() + owned.callback(os.close, event_read) + child.callback(os.close, event_write) + args = [sys.executable, "-I", "-c", WIRE["LAUNCH"], str(control_read), + str(event_write), str(binary), "-quiet", "-std=c++26", "-freflection", + "-fsyntax-only", "-nostdinc", "-fdiagnostics-format=sarif-stderr", + *flags, "query.cpp", "-o", os.devnull] + proc = subprocess.Popen(args, cwd=work, env=env, start_new_session=True, + pass_fds=(control_read, event_write, snapshot_fd), + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + owned.callback(proc.stdout.close) + owned.callback(proc.stderr.close) + mux = owned.enter_context(selectors.DefaultSelector()) + for stream, channel in ((event_read, "trace"), (proc.stdout, "stdout"), (proc.stderr, "stderr")): + mux.register(stream, selectors.EVENT_READ, channel) + buffers = {key: bytearray() for key in ("trace", "stdout", "stderr")} + try: + while mux.get_map(): + for key, _ in mux.select(remaining()): + chunk = os.read(key.fd, 16384) + if not chunk: + mux.unregister(key.fileobj) + continue + buf = buffers[key.data] + limit = TRACE_LIMIT if key.data == "trace" else SIDE_LIMIT + check(len(buf) + len(chunk) <= limit, f"{key.data} exceeded {limit} bytes") + buf.extend(chunk) + code = proc.wait(timeout=remaining()) + except BaseException: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + proc.wait(timeout=2) + raise + stderr = bytes(buffers["stderr"]) + check(code == expected, f"cc1plus exit {code}, expected {expected}: {stderr[:800]!r}") + check(not buffers["stdout"], f"unexpected compiler stdout: {buffers['stdout'][:200]!r}") + trace = bytes(buffers["trace"]) + check(not trace or trace.endswith(b"\n"), "incomplete final frame") + lines = trace.split(b"\n")[:-1] + check(len(lines) <= 4096, "event-count limit") + events = [] + for index, line in enumerate(lines): + check(len(line) + 1 <= 4096, "oversized event") + event = strict_json(line) + check(isinstance(event, dict) and type(event.get("v")) is int and event["v"] == 1 + and type(event.get("seq")) is int and event["seq"] == index + and event.get("nonce") == nonce, f"invalid v1 envelope at {index}") + events.append(event) + return Result(data, digest, nonce, proc.pid, events, stderr) + + +def point(source, line, spelling, ordinal=0): + raw = source.splitlines()[line - 1] + pattern = rb"(?= 3 and events[0]["kind"] == "hello" + and events[-2]["kind"] == "ideCoverage" and events[-1]["kind"] == "frontendEnd", + f"missing IDE handshake, final coverage or frontend end: {events[:2]}") + hello, coverage = events[0], events[-2] + check(hello["backend"] == "gcc-16.2.0/vls-ide-1" and hello["pid"] == result.pid + and hello["snapshot"] == result.snapshot and set(hello["kinds"]) == KINDS + and hello["capabilities"] == ["primaryFileOccurrences"], f"wrong IDE handshake {hello}") + check(coverage["source"] == "query.cpp" and coverage["reason"] == reason + and coverage["state"] == ("unavailable" if reason else "partial") + and all(type(coverage[k]) is bool for k in ("tentative", "unmapped", "unsupported", "conflict")), + f"wrong coverage {coverage}") + facts = {} + for event in events[1:-2]: + check(event["kind"] == "occurrence" and event["sourceKind"] == "primaryFileToken" + and event["role"] in ("field", "call") and type(event["declUid"]) is int + and event["declUid"] > 0 and event["resultType"] in ("int", "double") + and re.fullmatch(r"[a-zA-Z_]\w{0,63}", event["name"], re.ASCII), f"bad fact {event}") + use = read_span(event["use"], result, event["name"]) + check(use not in facts, f"duplicate fact at {use}") + target = None + if event["targetKind"] == "unavailable": + check(event["target"] is None, "unavailable target with a location") + else: + check(event["targetKind"] in ("definition", "declaration"), f"bad target {event}") + target = read_span(event["target"], result, event["name"]) + facts[use] = (event["role"], event["resultType"], event["targetKind"], target, event["declUid"]) + check(reason is None or not facts, f"positive occurrence after {reason}") + return facts, coverage + + +def witness(result, role, name, use_line, target_line, result_type, *, + use_ordinal=0, target_ordinal=0, target_kind="definition"): + facts, _ = inspect(result) + use = point(result.source, use_line, name, use_ordinal) + target = point(result.source, target_line, name, target_ordinal) + check(use in facts and facts[use][:4] == (role, result_type, target_kind, target), + f"missing {role} from {use} to {target}: {facts}") + return facts[use][4] + + +def missing_region(result): + payload = strict_json(result.stderr) + diagnostics = payload["runs"][0]["results"] + match = next(entry for entry in diagnostics if entry["level"] == "error" and + "missing" in entry["message"]["text"]) + location = match["locations"][0]["physicalLocation"] + check(location["artifactLocation"]["uri"] == "query.cpp", "wrong diagnostic source") + return location["region"] + + +def verify(binary): + saved = (HERE / "gcc-queries.cpp").read_text() + edited = saved.replace("Point point)", "Point point, double weight)").replace("coordinate(point)", "coordinate(weight)") + original, changed = run(binary, saved), run(binary, edited) + witness(original, "field", "x", 6, 3, "int") + witness(original, "call", "coordinate", 11, 6, "int") + witness(changed, "call", "coordinate", 11, 7, "double") + broken = run(binary, edited.replace("coordinate(weight)", "missing(weight)"), expected=1) + inspect(broken, "compileErrors") + region = missing_region(broken) + check((region["startLine"], region["startColumn"], region["endColumn"]) == (11, 20, 27), + f"incorrect ASCII diagnostic {region}") + witness(run(binary, saved), "call", "coordinate", 11, 6, "int") + print("Observed field and overload definitions, changed overload, invalid edit and recovery") + + for reverse in (False, True): + args = ("1.0", "point") if reverse else ("point", "1.0") + pair = run(binary, saved.replace("shapes::coordinate(point)", + f"shapes::coordinate({args[0]}) + shapes::coordinate({args[1]})")) + a = witness(pair, "call", "coordinate", 11, 7 if reverse else 6, "double" if reverse else "int") + b = witness(pair, "call", "coordinate", 11, 6 if reverse else 7, "int" if reverse else "double", + use_ordinal=1) + check(a != b, "two overloads have the same declaration identity in one invocation") + fields = run(binary, "struct A{int x;};\nstruct B{double x;};\ndouble q(A a,B b){return a.x+b.x;}\n") + first = witness(fields, "field", "x", 3, 1, "int") + second = witness(fields, "field", "x", 3, 2, "double", use_ordinal=1) + check(first != second, "distinct field owners collapsed") + qualified = run(binary, "struct Base { int x; }; using x=Base; int q(Base b){return b.x::x;}\n") + witness(qualified, "field", "x", 1, 1, "int", use_ordinal=3) + check(point(qualified.source, 1, "x", 2) not in inspect(qualified)[0], "published a qualifier as field use") + print("Distinguished same-line overloads, same-spelling fields and a same-spelling qualifier") + + bom = run(binary, "\ufeffnamespace x { int x(int); } int q(){return x::x(1);}\n" + "namespace x { int x(int n){return n;} }\n") + witness(bom, "call", "x", 1, 2, "int", use_ordinal=3, target_ordinal=1) + check(point(bom.source, 1, "x", 2) not in inspect(bom)[0], + "first-line BOM shifted a call to its same-spelling qualifier") + first_line_target = run(binary, "\ufeffint f(){return 1;}\nint q(){return f();}\n") + witness(first_line_target, "call", "f", 2, 1, "int") + print("Verified physical byte positions for a BOM-prefixed call and definition") + + prototype = "int only(int); int use(){return only(1);}" + witness(run(binary, prototype), "call", "only", 1, 1, "int", use_ordinal=1, target_kind="declaration") + witness(run(binary, prototype + " int only(int a){return a;}"), "call", "only", 1, 1, "int", + use_ordinal=1, target_ordinal=2) + line_remap = "int call(int x){return x;}\n#line 11\nint a(){return call(1);}\n#line 11\nint b(){return call(2);}\n" + inspect(run(binary, line_remap), "lineDirective") + macro = run(binary, "int call(int p){return p;}\n#define SITE call\nint q(){return SITE(1);}\n") + facts, coverage = inspect(macro) + check(not facts and coverage["unmapped"], "macro use escaped the provenance gate") + tentative = run(binary, "struct Box{int x;}; int q(Box a){return sizeof(decltype(a.x));}\n") + facts, coverage = inspect(tentative) + check(not facts and coverage["tentative"], "speculative member access was published") + print("Verified forward declaration, later definition, ambiguous line map, macro use and tentative parse") + + utf = "int q(){\t/*🙂e\u0301*/ return missing(1);}\n" + failure = run(binary, utf, expected=1) + inspect(failure, "compileErrors") + display = missing_region(failure)["startColumn"] + prefix = utf.partition("missing")[0] + byte = len(prefix.encode()) + 1 + utf16 = len(prefix.encode("utf-16-le")) // 2 + 1 + check((display, byte, utf16) == (32, 29, 26), "Unicode diagnostic coordinate witness failed") + utf_success = run(binary, "int only(int a){return a;}\n" + + utf.replace("missing(1)", "only(1)")) + witness(utf_success, "call", "only", 2, 1, "int") + print("Verified UTF-8 token bytes and three distinct SARIF display, byte and UTF-16 columns") + + for flags, valid in ((IDE, False), (("-fvls-ide",), True), ((*IDE, "-fvls-step"), True)): + denied = run(binary, saved, flags=flags, expected=1, valid_digest=valid) + check(not denied.events and denied.stderr, "invalid IDE setup produced events") + check(not run(binary, saved, flags=()).events, "disabled hooks emitted an event") + print("Verified mode isolation, snapshot identity and disabled hooks") + + +if __name__ == "__main__": + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--cc1plus", type=Path, required=True) + verify(ap.parse_args().cc1plus.resolve(strict=True)) diff --git a/tests/corpus/frontend/verify-gcc.py b/tests/corpus/frontend/verify-gcc.py new file mode 100644 index 0000000..8769c17 --- /dev/null +++ b/tests/corpus/frontend/verify-gcc.py @@ -0,0 +1,72 @@ +"""Run the Void C++26 reference cases with GCC in a private module cache.""" + +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + + +FIXTURES = Path(__file__).resolve().parent + + +def check_case(name, argv, work, *, diagnostic=None, stdout=None): + result = subprocess.run( + argv, cwd=work, env={**os.environ, "LC_ALL": "C"}, timeout=45, + capture_output=True, text=True, errors="replace", + ) + if diagnostic is None: + matched = result.returncode == 0 + else: + matched = result.returncode == 1 and diagnostic in result.stderr + if not matched or (stdout is not None and result.stdout.strip() != stdout): + raise SystemExit( + f"{name}: exit {result.returncode}\n{result.stdout}\n{result.stderr}" + ) + print(f"{name}: exit {result.returncode}") + + +def verify(compiler, include, work): + flags = [compiler, "-std=c++26", "-freflection", "-fdiagnostics-color=never"] + syntax = ["-fsyntax-only"] + for public in (False, True): + name = "public" if public else "detail" + defines = ["-DPUBLIC_ENTRY"] if public else [] + program = work / f"enum-{name}" + check_case(f"compile {name} enum helper", + [*flags, *defines, "-I", include, FIXTURES / "enum.cpp", "-o", program], work) + check_case(f"run {name} enum helper", [program], work, stdout="Ready ? 17 0 41 0") + + check_case("GCC reflection library", [*flags, *syntax, FIXTURES / "library.cpp"], work) + check_case("library without reflection", + [compiler, "-std=c++26", "-fno-reflection", *syntax, FIXTURES / "library.cpp"], + work, diagnostic="GCC 16.2 reflection declarations are inactive") + check_case("constexpr span with static storage", [*flags, *syntax, FIXTURES / "range-static.cpp"], work) + check_case("constexpr span with automatic storage", [*flags, *syntax, FIXTURES / "range.cpp"], + work, diagnostic="constant expression") + for defines in ([], ["-DINIT_LIST"]): + check_case("constexpr range expansion", [*flags, *defines, *syntax, FIXTURES / "expansion-static.cpp"], work) + + provider = ["-x", "c++", "-c", FIXTURES / "gate.cppm", "-o", "gate.o"] + importer = ["-c", FIXTURES / "importer.cpp", "-o", "importer.o"] + modules = [*flags, "-fmodules"] + check_case("import before module is built", [*modules, *importer], work, diagnostic="gate") + check_case("provider without module flag", [*flags, *provider], work, diagnostic="-fmodules") + check_case("module interface", [*modules, *provider], work) + check_case("module importer", [*modules, *importer], work) + check_case("link module program", [compiler, "gate.o", "importer.o", "-o", "module"], work) + check_case("run imported reflection", [work / "module"], work) + for source, location in (("invalid-name.cpp", ":4:48:"), ("invalid-splice.cpp", ":5:35:")): + check_case(f"diagnose {source}", [*modules, *syntax, FIXTURES / source], work, + diagnostic=source + location) + check_case("valid importer after invalid edit", [*modules, *syntax, FIXTURES / "importer.cpp"], work) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cxx", default="g++", help="GCC 16+ C++ compiler") + parser.add_argument("--void-include", type=Path, required=True, help="tested VoidLibrary include directory") + args = parser.parse_args() + include = args.void_include.resolve(strict=True) + with tempfile.TemporaryDirectory(prefix="vls-gcc-corpus-") as scratch: + verify(args.cxx, include, Path(scratch)) diff --git a/tests/corpus/frontend/verify-stock-diagnostics.py b/tests/corpus/frontend/verify-stock-diagnostics.py new file mode 100644 index 0000000..25331bf --- /dev/null +++ b/tests/corpus/frontend/verify-stock-diagnostics.py @@ -0,0 +1,300 @@ +"""Exercise the VLS diagnostic adapter with an unmodified GCC and a real native Void TU.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import shlex +import shutil +import subprocess +import tempfile + + +ROOT = Path(__file__).resolve().parents[3] +TU = ROOT / "src/Documents/DocumentSnapshot.cpp" +LIB_INCLUDE = ROOT / "build/voidlibrary/current/include" +MAX_REPORT = 4 * 1024 * 1024 + + +def check(condition, detail): + if not condition: + raise ValueError(detail) + + +def checked_command(fixture, compiler, database=None): + command = [fixture, "--command", ROOT, TU, compiler] + if database: + command.append(database) + result = subprocess.run(command, capture_output=True, text=True, timeout=30) + check(result.returncode == 0 and not result.stderr, + f"could not acquire a checked editor compiler context: {result.stderr}") + row = json.loads(result.stdout) + with open(compiler, "rb") as binary: + digest = hashlib.file_digest(binary, "sha256").hexdigest() + check(row["provider"] == ("compdb" if database else "vbs") and Path(row["directory"]).is_absolute() + and row["file"] == str(TU) and row["driverSha256"] == digest, "wrong compiler lease") + return row + + +def native_flags(fixture, compiler, expected): + selected = checked_command(fixture, compiler) + path = Path(selected["database"]) + check(expected is None or path == expected, "the selected native VBS generation changed") + check(path.stat().st_size <= 16 * 1024 * 1024, "oversized compilation database") + rows = json.loads(path.read_bytes()) + matches = [r for r in rows if r.get("file") == str(TU)] + check(len(matches) == 1, "the native fixture requires one command for DocumentSnapshot.cpp") + row = matches[0] + args = row["arguments"] + check(Path(args[0]).samefile(compiler) and row["directory"] == selected["directory"] == str(ROOT), + "the native fixture and selected stock compiler must agree") + check(args[-4:] == ["-c", str(TU), "-o", row["output"]], "unexpected native output operands") + check(selected["arguments"] == args[:-2], "C++ lease and native semantic argument order disagree") + flags = selected["arguments"][1:-2] + roots = {str(ROOT / "include"), str(LIB_INCLUDE.resolve(strict=True))} + accepted = {"-std=c++26", "-freflection", "-DVOID_CRYPTO_HAS_OPENSSL=0", "-g", "-O0", "-O2", + "-O3", "-DNDEBUG"} + i = 0 + while i < len(flags): + if flags[i] == "-I": + check(i + 1 < len(flags) and flags[i + 1] in roots, "unexpected fixture include root") + i += 2 + else: + check(flags[i] in accepted, f"unexpected native fixture argument {flags[i]!r}") + i += 1 + check(roots.issubset(flags) and {"-std=c++26", "-freflection"}.issubset(flags), + "incomplete native C++26 fixture command") + return flags + + +def capture_report(argv, cwd, status): + with tempfile.TemporaryFile() as report, tempfile.TemporaryFile() as output: + proc = subprocess.run(argv, cwd=cwd, env={**os.environ, "LC_ALL": "C"}, + stdin=subprocess.DEVNULL, stdout=output, stderr=report, timeout=45) + size = report.tell() + check(0 < size <= MAX_REPORT and output.tell() == 0, "incomplete GCC diagnostic output") + report.seek(0) + wire = report.read() + check(proc.returncode == status, f"GCC exit {proc.returncode}, expected {status}: {wire[:400]!r}") + return wire + + +def compile_report(compiler, flags, source, status): + return capture_report([compiler, *flags, "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", + source.name], source.parent, status) + + +def observe(fixture, compiler, flags, source, text, status, witness=()): + source.write_text(text, encoding="utf-8") + report = compile_report(compiler, flags, source, status) + result = subprocess.run([fixture, source.name, str(status), *map(str, witness)], cwd=source.parent, + input=report, capture_output=True, check=True, timeout=10) + check(not result.stderr, result.stderr) + return json.loads(result.stdout), json.loads(report)["runs"][0] + + +def clean(result): + check(result == {"complete": True, "diagnostics": []}, f"expected a clean owner: {result!r}") + + +def isolated_inputs(fixture, compiler, flags, work): + """Nix/Linux fixture. Mount only the known compiler and fixture inputs at their original paths.""" + def captured_input(path, edited=None): + mode = "--capture-disk" if edited is None else "--capture-overlay" + proc = subprocess.run([fixture, mode, ROOT, TU, compiler, path], input=edited or b"", + capture_output=True, timeout=30) + check(proc.returncode == 0 and not proc.stderr, f"source capture failed: {proc.stderr!r}") + entry = json.loads(proc.stdout) + check(entry["uri"] == path.as_uri() and entry["overlay"] == (edited is not None), + f"source capture returned the wrong binding for {path}") + data = entry["text"].encode("utf-8") + if edited is not None: + check(data == edited, "captured bytes lost an editor change") + return data + + bwrap, store = shutil.which("bwrap"), shutil.which("nix-store") + check(bwrap and store, "isolated fixture requires bubblewrap and nix-store") + frontend = Path(subprocess.check_output([compiler, "-print-prog-name=cc1plus"], + timeout=10, text=True).strip()).resolve(strict=True) + check(frontend.is_relative_to("/nix/store") and len(frontend.parts) > 4, "expected a Nix GCC package") + package = Path(*frontend.parts[:4]) + closure = {Path(p) for p in subprocess.check_output([store, "-qR", package], timeout=20, + text=True).splitlines()} + check(0 < len(closure) <= 128 and all(p.parent == Path("/nix/store") for p in closure), + "unexpected compiler runtime closure") + probe = subprocess.run([compiler, "-###", *flags, "-frandom-seed=vls-test-view", "-fsyntax-only", + "-fdiagnostics-format=sarif-stderr", TU], cwd=ROOT, capture_output=True, + text=True, check=True, timeout=15, env={**os.environ, "LC_ALL": "C"}) + cmds = [shlex.split(line) for line in probe.stderr.splitlines() + if line.lstrip().startswith((str(frontend) + " ", '"' + str(frontend) + '" '))] + check(len(cmds) == 1 and cmds[0][0] == str(frontend) and cmds[0].count(str(TU)) == 1, + "could not identify one GCC frontend for the original translation unit") + args = cmds[0] + system_dirs = {Path(args[i + 1]) for i, arg in enumerate(args[:-1]) + if arg in {"-isystem", "-idirafter"}} + check(all(p.is_relative_to("/nix/store") and p.is_dir() for p in system_dirs), + "expected immutable toolchain include directories") + sandbox = [bwrap, "--unshare-all", "--die-with-parent", "--new-session", "--clearenv", + "--setenv", "LC_ALL", "C", "--dev", "/dev", "--tmpfs", "/tmp"] + for p in sorted(closure | {p for p in system_dirs if not any(p.is_relative_to(k) for k in closure)}): + sandbox.extend(["--ro-bind", p, p]) + + include = work / "vls-headers" + for name in ("DocumentSnapshot.hpp", "Position.hpp", "Uri.hpp"): + relative = Path("Void/LanguageServer/Documents", name) + dest = include / relative + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(captured_input(ROOT / "include" / relative)) + deps = LIB_INCLUDE.resolve(strict=True) + original = captured_input(TU) + text = original.decode("utf-8") + saved = work / "saved-input.cpp" + saved.write_bytes(original) + broken = work / "broken-input.cpp" + broken.write_bytes(captured_input(TU, text.replace("Void::Hash::fnv1a64(text)", + "Void::Hash::missing(text)").encode())) + line, = [i for i, s in enumerate(broken.read_text().splitlines(), 1) if "Void::Hash::missing(text)" in s] + first = broken.read_text().splitlines()[line - 1].index("missing") + 1 + end = first + len("missing") + + def compile_view(source, code, witness=(), additional=()): + mounts = [(include, ROOT / "include"), (deps, deps), (source, TU), *additional] + command = [*sandbox] + for src, dst in mounts: + command.extend(["--ro-bind", src, dst]) + wire = capture_report([*command, "--chdir", ROOT, "--", *args], work, code) + out = subprocess.run([fixture, "--logical-file", TU, source.name, str(code), *map(str, witness)], + cwd=work, input=wire, capture_output=True, check=True, timeout=10) + check(not out.stderr, out.stderr) + return json.loads(out.stdout) + + clean(compile_view(saved, 0)) + batch = compile_view(broken, 1, (line, first, end)) + check(batch["complete"] and any(d["range"] == [[line-1, first-1], [line-1, end-1]] and + "missing" in d["message"] for d in batch["diagnostics"]), batch) + clean(compile_view(saved, 0)) + + header = Path("Void/Core/Hash.hpp") + overlay = work / "Hash.hpp" + overlay.write_bytes(captured_input(deps / header, b'#error "VLS private header snapshot"\n' + + captured_input(deps / header))) + header_error = compile_view(saved, 1, additional=[(overlay, deps / header)]) + check(any("VLS private header snapshot" in d["message"] for d in header_error["diagnostics"]), + "the compiler ignored the staged header at its original name") + clean(compile_view(saved, 0)) + + # A benign host-only file distinguishes a private lookup domain from accidental fallback. + marker = work / "host-only.hpp" + marker.write_text("// fixture\n", encoding="ascii") + lookup = work / "lookup.cpp" + lookup.write_bytes(captured_input(TU, (f'#if __has_include("{marker}")\n' + '#error host-only file visible\n#endif\n' + text).encode())) + outside = json.loads(compile_report(compiler, flags, lookup, 1))["runs"][0] + check(any("host-only file visible" in d["message"]["text"] for d in outside["results"]), + "missing ambient positive control") + clean(compile_view(lookup, 0)) + check(TU.read_bytes() == original, "the original TU was modified") + print(f"private source view: {len(closure)} compiler runtime paths, saved/edit/recover, " + "header overlay and __has_include controls passed") + + +def run(fixture, compiler, database, work): + flags = native_flags(fixture, compiler, database) + path = work / TU.name + text = TU.read_text(encoding="utf-8") + call = "Void::Hash::fnv1a64(text)" + check(text.count(call) == 1, "the real Void overload witness changed") + modified = text.replace(call, "Void::Hash::fnv1a64(std::as_bytes(std::span{text}))") + broken = text.replace(call, "Void::Hash::missing(text)") + line, = [i for i,s in enumerate(broken.splitlines(), 1) if "Void::Hash::missing(text)" in s] + first = broken.splitlines()[line-1].index("missing") + 1 + end = first + len("missing") + clean(observe(fixture, compiler, flags, path, text, 0)[0]) + clean(observe(fixture, compiler, flags, path, modified, 0)[0]) + batch, _ = observe(fixture, compiler, flags, path, broken, 1, (line, first, end)) + matches = [d for d in batch["diagnostics"] if "missing" in d["message"]] + check(batch["complete"] and len(matches) == 1 and + matches[0]["range"] == [[line-1, first-1], [line-1, end-1]], batch) + clean(observe(fixture, compiler, flags, path, text, 0)[0]) + print(f"stock GCC: saved, overload edit, source error at {line}:[{first},{end}), restored") + + # Change just the copied overload attributes. The two messages independently identify + # the overload selected by the compiler when the caller's argument type changes. + relative = Path("Void/Core/Hash.hpp") + original = (LIB_INCLUDE / relative).read_bytes() + header = original.decode("utf-8") + for signature, tag in (("fnv1a64(std::string_view s)", "string_view"), + ("fnv1a64(std::span data)", "byte_span")): + check(header.count(signature) == 1, signature) + start = header.rindex("[[nodiscard]]", 0, header.index(signature)) + header = header[:start] + header[start:].replace( + "[[nodiscard]]", f'[[nodiscard, deprecated("vls-diagnostic-{tag}")]]', 1) + overlay_root = work / "header" + overlay = overlay_root / relative + overlay.parent.mkdir(parents=True) + overlay.write_text(header, encoding="utf-8") + insert = flags.index(str(LIB_INCLUDE.resolve())) - 1 + header_flags = [*flags[:insert], "-I", str(overlay_root), *flags[insert:]] + for caller, tag in ((text, "string_view"), (modified, "byte_span")): + batch, raw = observe(fixture, compiler, header_flags, path, caller, 0) + matched = [r for r in raw["results"] if f"vls-diagnostic-{tag}" in r["message"]["text"] and + any(loc["physicalLocation"]["artifactLocation"].get("uri") == path.name and + loc["physicalLocation"]["region"]["startLine"] == line for loc in r["locations"])] + check(len(matched) == 1 and any(d["message"] == matched[0]["message"]["text"] for d in + batch["diagnostics"]), f"missing overload evidence for {tag}") + check(all(d["range"] is None for d in batch["diagnostics"]), "range without a physical witness") + overlay.write_bytes(original) + clean(observe(fixture, compiler, header_flags, path, text, 0)[0]) + check((LIB_INCLUDE / relative).read_bytes() == original, "prepared dependency changed") + print("stock GCC: staged header reports string_view, then byte_span, then clears on restoration") + + path = work / "main.cpp" + inactive = "int q(){return missing;}" + (work / "alias.hpp").write_text('#line 2 "main.cpp"\n' + inactive + "\n", encoding="utf-8") + batch, raw = observe(fixture, compiler, ["-std=c++26", "-freflection"], path, + "#if 0\n" + inactive + '\n#endif\n#include "alias.hpp"\n', 1) + locations = raw["results"][0]["locations"] + check(any(loc["physicalLocation"]["artifactLocation"]["uri"] == "main.cpp" and + loc["physicalLocation"]["region"]["startLine"] == 2 for loc in locations), + "expected GCC to remap the header to the inactive main line") + check(not batch["complete"] and any("missing" in d["message"] and d["range"] is None + for d in batch["diagnostics"]), batch) + print("stock GCC: header remapped to an inactive source line retained an unlocated message") + return flags + + +if __name__ == "__main__": + cli = argparse.ArgumentParser(description=__doc__) + cli.add_argument("--fixture", required=True, type=Path) + cli.add_argument("--database", type=Path, help="assert this is the selected native VBS compilation database") + cli.add_argument("--comparison", type=Path, help="also acquire the real TU from this compile_commands.json") + cli.add_argument("--cxx", default="g++") + cli.add_argument("--isolated-inputs", action="store_true", + help="also verify a private Linux/Nix input view with bubblewrap") + options = cli.parse_args() + compiler = shutil.which(options.cxx) + if not compiler: + cli.error(f"compiler not found: {options.cxx}") + with tempfile.TemporaryDirectory(prefix="vls-stock-diagnostic-") as temp: + fixture = options.fixture.resolve(strict=True) + for directory in ("left right", "left%20right"): + work = Path(temp) / directory + work.mkdir() + result, run_data = observe(fixture, compiler, ["-std=c++26"], work / "unit.cpp", + "int x;\n", 0) + clean(result) + check(run_data["originalUriBaseIds"]["PWD"]["uri"] == f"file://{work}/", + "GCC working-directory spelling changed") + database = options.database.resolve(strict=True) if options.database else None + flags = run(fixture, compiler, database, Path(temp)) + if options.comparison: + comparison = options.comparison.resolve(strict=True) + compat = checked_command(fixture, compiler, comparison) + expected_rows = [r for r in json.loads(comparison.read_bytes()) if r["file"] == str(TU)] + check(len(expected_rows) == 1 and compat["directory"] == expected_rows[0]["directory"] + and compat["database"] == str(comparison) and "-freflection" in compat["arguments"], + "incomplete compatibility compiler context") + print("compile_commands: acquired and revalidated the selected real Void translation unit") + if options.isolated_inputs: + isolated_inputs(fixture, compiler, flags, Path(temp)) diff --git a/tests/corpus/frontend/verify-stock-gcc-gdb.py b/tests/corpus/frontend/verify-stock-gcc-gdb.py new file mode 100644 index 0000000..1d2837c --- /dev/null +++ b/tests/corpus/frontend/verify-stock-gcc-gdb.py @@ -0,0 +1,140 @@ +"""Observe nested consteval returns on stock x86-64 Linux GCC 16.2 using GDB.""" + +import argparse +import json +from pathlib import Path +import subprocess +import sys +import tempfile + + +def observe(gdb): + # The type object is loaded only in GDB. The installed cc1plus runs the + # original source with its ordinary flags and receives no plugin. + tree = gdb.lookup_type("tree_node").pointer() + codes = {name: int(gdb.parse_and_eval(name)) for name in + ("CALL_EXPR", "ADDR_EXPR", "FUNCTION_DECL", "IDENTIFIER_NODE", "INTEGER_CST")} + + def code(node): + return int(node["base"]["code"]) + + def operand(node, index): + return (node["exp"]["operands"][0].address + index).dereference() + + def callee(call): + if code(call) != codes["CALL_EXPR"]: + return None + function = operand(call, 1) + if function and code(function) == codes["ADDR_EXPR"]: + function = operand(function, 0) + if not function or code(function) != codes["FUNCTION_DECL"]: + return None + identifier = function["decl_minimal"]["name"] + if not identifier or code(identifier) != codes["IDENTIFIER_NODE"]: + return None + entry = identifier["identifier"]["id"] + length = int(entry["len"]) + if 0 < length <= 64: + return entry["str"].string(length=length) + return None + + hits = [] + active = [] + observations = [] + + class Entry(gdb.Breakpoint): + def stop(self): + hits.append((None, None)) + return True + + class Return(gdb.FinishBreakpoint): + def __init__(self, name): + super().__init__(gdb.newest_frame(), internal=True) + self.function_name = name + + def stop(self): + result = gdb.newest_frame().read_register("rax").cast(tree) + value = int(result["int_cst"]["val"][0]) if result and code(result) == codes["INTEGER_CST"] else None + hits.append((self.function_name, value)) + return True + + # The unmodified package retains this out-of-line function symbol. + # rsi and rax are the second argument and return registers of this ABI. + signature = "cxx_eval_call_expression(constexpr_ctx const*, tree_node*, value_cat, bool*, bool*, tree_node**)" + Entry(f"*'{signature}'", internal=True) + command = "run" + for _ in range(1024): + hits.clear() + stopped = gdb.execute(command, to_string=True) + if not gdb.selected_inferior().pid: + break + if len(hits) != 1: + raise RuntimeError(f"Unexpected stop {hits}: {stopped}") + frame = gdb.newest_frame() + name, value = hits[0] + if name is None: + name = callee(frame.read_register("rsi").cast(tree)) + if name in ("twice", "reflected_value"): + active.append(name) + Return(name) + else: + if not active or active.pop() != name: + raise RuntimeError("Unexpected evaluator return order") + observations.append([name, active.copy(), value, gdb.selected_inferior().pid]) + command = "continue" + else: + raise RuntimeError("Exceeded the fixture stop limit") + if active or int(gdb.parse_and_eval("$_exitcode")) != 0: + raise RuntimeError("Incomplete stock compiler run") + print("VLS_STOCK_RETURNS " + json.dumps(observations)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cxx", default="g++") + parser.add_argument("--gdb", default="gdb") + parser.add_argument("--include-dir", action="append", default=[], type=Path, + help="additional header directory for building the GDB type object") + args = parser.parse_args() + + def compiler_value(option): + return subprocess.check_output([args.cxx, option], text=True, timeout=10).strip() + + target = compiler_value("-dumpmachine") + if compiler_value("-dumpfullversion") != "16.2.0" or not target.startswith("x86_64-") or "linux" not in target: + parser.error("this fixture adapter covers x86-64 Linux GCC 16.2.0") + frontend = compiler_value("-print-prog-name=cc1plus") + headers = Path(compiler_value("-print-file-name=plugin")) / "include" + script = Path(__file__).resolve() + fixture = script.with_name("gcc-live.cpp").read_text() + if fixture.count("Ready = 17") != 1: + raise RuntimeError("Missing the unique fixture edit") + + with tempfile.TemporaryDirectory(prefix="vls-stock-gcc-") as temporary: + directory = Path(temporary) + (directory / "types.cc").write_text( + '#include "gcc-plugin.h"\n#include "tree.h"\n' + 'tree_node *vls_debug_tree;\ntree_code vls_debug_code;\n') + includes = [f"-I{path.resolve()}" for path in [headers, *args.include_dir]] + subprocess.run([args.cxx, "-g", "-O0", "-c", *includes, "types.cc", "-o", "types.o"], + cwd=directory, check=True, timeout=30) + for value in (17, 41): + (directory / "fixture.cpp").write_text(fixture.replace("Ready = 17", f"Ready = {value}")) + command = [args.gdb, "-nx", "-nh", "-q", "-batch", "-iex", "set auto-load off", + "-iex", "set debuginfod enabled off", "-ex", "add-symbol-file types.o 0", + "-x", str(script), "--args", frontend, "-quiet", "-std=c++26", "-freflection", + "-fsyntax-only", "-nostdinc", "fixture.cpp", "-o", "/dev/null"] + output = subprocess.check_output(command, cwd=directory, text=True, timeout=20) + prefix = "VLS_STOCK_RETURNS " + rows, = (json.loads(line[len(prefix):]) for line in output.splitlines() if line.startswith(prefix)) + pairs = [(inner[2], outer[2]) for inner, outer in zip(rows, rows[1:]) + if inner[:2] == ["reflected_value", ["twice"]] and outer[:2] == ["twice", []]] + if pairs != [(value, 2 * value), (value + 5, 2 * (value + 5))] or len({row[3] for row in rows}) != 1: + raise RuntimeError(f"Unexpected stock compiler observations {rows}") + print(f"Stock GCC 16.2 returned {pairs} live in PID {rows[0][3]}.") + + +if "gdb" in sys.modules: + observe(sys.modules["gdb"]) +elif __name__ == "__main__": + main() diff --git a/tests/corpus/frontend/verify-stock-observer.py b/tests/corpus/frontend/verify-stock-observer.py new file mode 100755 index 0000000..9ee767f --- /dev/null +++ b/tests/corpus/frontend/verify-stock-observer.py @@ -0,0 +1,399 @@ +#!/usr/bin/env python3 +"""Verify the stock GCC occurrence observer against closed, byte-checked fixtures.""" + +import argparse +import json +import os +from pathlib import Path +import re +import secrets +import shutil +import subprocess +import tempfile + + +MAX_REPORT = 1024 * 1024 +HEX = re.compile(r"[0-9a-f]{32}") + + +def check(condition, detail): + if not condition: + raise ValueError(detail) + + +def unique_keys(pairs): + result = {} + for key, value in pairs: + check(key not in result, f"duplicate JSON key {key!r}") + result[key] = value + return result + + +def reject_constant(value): + raise ValueError(f"non-finite JSON number {value}") + + +def strict_json(data): + return json.loads(data.decode("utf-8", errors="strict"), object_pairs_hook=unique_keys, + parse_constant=reject_constant) + + +def compiler(): + selected = shutil.which("g++") + check(selected, "g++ not found") + return Path(selected).resolve(strict=True) + + +def manifest(work, nonce, paths): + lines = ["VLS-OCCURRENCES-1", nonce, *(str(path) for path in paths)] + (work / "inputs").write_text("\n".join(lines) + "\n", encoding="utf-8") + return work / "inputs" + + +def compile(compiler, observer, work, main, flags=()): + env = {**os.environ, "LC_ALL": "C", "TZ": "UTC0", + "VLS_OBSERVER_INPUTS": str(work / "inputs"), + "VLS_OBSERVER_OUTPUT": str(work / "report")} + argv = [compiler, "-std=c++26", "-freflection", "-fsyntax-only", *flags, + f"-fplugin={observer}", str(main)] + return subprocess.run(argv, cwd=work, env=env, stdin=subprocess.DEVNULL, + capture_output=True, timeout=120) + + +def read_span(span, name, label): + check(isinstance(span, dict) and set(span) == {"path", "line", "startByte", "endByte"}, + f"invalid {label} span {span!r}") + check(all(type(span[key]) is int for key in ("line", "startByte", "endByte")), + f"non-integer {label} span {span!r}") + path = Path(span["path"]) + check(path.is_absolute() and path.is_file(), f"{label} path is not an admitted file: {path}") + lines = path.read_bytes().split(b"\n") + check(1 <= span["line"] <= len(lines), f"{label} line outside {path}: {span}") + raw = lines[span["line"] - 1] + start, end = span["startByte"], span["endByte"] + check(1 <= start < end <= len(raw) + 1, f"{label} bytes outside line: {span}") + check(raw[start - 1:end - 1] == name.encode("ascii"), + f"{label} {name!r} does not occupy {span}: {raw!r}") + raw[:start - 1].decode("utf-8") + raw[:end - 1].decode("utf-8") + return (path, span["line"], start, end) + + +def analyze(work, nonce, admitted, complete=True, partial=None): + report_path = work / "report" + check(report_path.is_file(), "observer wrote no report") + data = report_path.read_bytes() + check(0 < len(data) <= MAX_REPORT, "report size out of bounds") + report = strict_json(data) + check(set(report) == {"schema", "nonce", "complete", "partial", "reason", "occurrences"}, + f"unexpected report keys {sorted(report)}") + check(type(report["schema"]) is int and report["schema"] == 1, "wrong schema") + check(report["nonce"] == nonce and HEX.fullmatch(report["nonce"]) is not None, "wrong nonce") + check(type(report["complete"]) is bool and type(report["partial"]) is bool, + "non-boolean status") + check(isinstance(report["reason"], str), "reason is not a string") + check(report["complete"] is complete, f"complete={report['complete']}, expected {complete}") + if partial is not None: + check(report["partial"] is partial, f"partial={report['partial']}, expected {partial}") + check((report["reason"] == "") is complete, f"reason {report['reason']!r} disagrees with status") + occurrences = report["occurrences"] + check(isinstance(occurrences, list), "occurrences is not a list") + seen = set() + for occurrence in occurrences: + check(isinstance(occurrence, dict), "occurrence is not an object") + check({"name", "type", "canonicalType", "use", "definition"} <= set(occurrence) + and set(occurrence) <= {"name", "type", "canonicalType", "signature", + "use", "definition"}, + f"unexpected occurrence keys {sorted(occurrence)}") + name = occurrence["name"] + check(re.fullmatch(r"[A-Za-z_]\w{0,63}", name, re.ASCII), f"bad name {name!r}") + check(isinstance(occurrence["type"], str) and occurrence["type"], "bad type") + check(isinstance(occurrence["canonicalType"], str) and occurrence["canonicalType"], + "bad canonical type") + if "signature" in occurrence: + signature = occurrence["signature"] + check(isinstance(signature, str) and 0 < len(signature) <= 300, "bad signature") + use = read_span(occurrence["use"], name, "use") + check(use[0] in admitted, f"use is outside the captured set: {use[0]}") + key = (use[0], use[1], use[2]) + check(key not in seen, f"duplicate use {key}") + seen.add(key) + if occurrence["definition"] is not None: + definition = read_span(occurrence["definition"], name, "definition") + check(definition[0] in admitted, + f"definition is outside the captured set: {definition[0]}") + return report + + +def case(compiler, observer, name, files, main, *, flags=(), status=0, nonce=None, + verify=None, complete=True, partial=None): + with tempfile.TemporaryDirectory(prefix="vls-observer-") as temp: + work = Path(temp) + for relative, content in files.items(): + path = work / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content if isinstance(content, bytes) else content.encode("utf-8")) + nonce = nonce or secrets.token_hex(16) + admitted = {(work / relative).resolve() for relative in files} + manifest(work, nonce, sorted(admitted)) + result = compile(compiler, observer, work, (work / main).resolve(), flags) + check(result.returncode == status, + f"{name}: compiler exit {result.returncode}, expected {status}: " + f"{result.stderr[-800:]!r}") + if not (work / "report").exists(): + check(status != 0, f"{name}: no report") + return None + report = analyze(work, nonce, admitted, complete=complete, partial=partial) + if verify: + verify(report, work) + print(f"{name}: ok") + return report + + +def by_name(report, name): + return [occurrence for occurrence in report["occurrences"] if occurrence["name"] == name] + + +def overload_case(compiler, observer): + source = """namespace shapes { +constexpr int coordinate(int value) { return value; } +constexpr double coordinate(double value) { return value; } +} +double query(int whole, double fraction) { + return shapes::coordinate(whole) + shapes::coordinate(fraction); +} +""" + def verify(report, work): + found = by_name(report, "coordinate") + check(len(found) == 2, f"expected two same-line overloads: {found}") + check({occurrence["type"] for occurrence in found} == {"int", "double"}, found) + definitions = {occurrence["definition"]["line"] for occurrence in found} + check(definitions == {2, 3}, f"overload definitions collapsed: {definitions}") + check(found[0]["use"]["line"] == found[1]["use"]["line"] == 6, found) + + case(compiler, observer, "same-line overloads", {"unit.cpp": source}, "unit.cpp", + verify=verify) + edited = source.replace("double fraction", "int fraction") + def verify_edited(report, work): + found = by_name(report, "coordinate") + check(len(found) == 2, f"expected two calls after the edit: {found}") + check({occurrence["type"] for occurrence in found} == {"int"}, found) + check({occurrence["definition"]["line"] for occurrence in found} == {2}, found) + + case(compiler, observer, "overload edit", {"unit.cpp": edited}, "unit.cpp", + verify=verify_edited) + + +def header_case(compiler, observer): + header = "int shifted(int value) {\n return value;\n}\n" + main = '#include "header.hpp"\nint q() { return shifted(3); }\n' + def verify(report, work): + found = by_name(report, "shifted") + check(len(found) == 1 and found[0]["definition"]["line"] == 1, found) + case(compiler, observer, "header definition", {"main.cpp": main, "header.hpp": header}, + "main.cpp", verify=verify) + shifted = "// a new first line\n" + header + def verify_shifted(report, work): + found = by_name(report, "shifted") + check(len(found) == 1 and found[0]["definition"]["line"] == 2, found) + check(found[0]["use"]["line"] == 2, found) + case(compiler, observer, "header shift", {"main.cpp": main, "header.hpp": shifted}, + "main.cpp", verify=verify_shifted) + + +def macro_case(compiler, observer): + source = "int call(int value) { return value; }\n#define SITE call\nint q() { return SITE(1); }\n" + def verify(report, work): + check(not by_name(report, "call"), "macro use escaped the provenance gate") + case(compiler, observer, "macro use", {"unit.cpp": source}, "unit.cpp", + verify=verify, partial=True) + + +def line_directive_case(compiler, observer): + source = "int call(int value) { return value; }\n#line 11\nint q() { return call(1); }\n" + def verify(report, work): + check(report["occurrences"] == [], "line remap published facts") + check(report["reason"] == "lineDirective", report["reason"]) + case(compiler, observer, "line directive", {"unit.cpp": source}, "unit.cpp", + complete=False, verify=verify) + + +def qualifier_case(compiler, observer): + source = "namespace x { int x(int value) { return value; } }\nint q() { return x::x(1); }\n" + def verify(report, work): + found = by_name(report, "x") + check(len(found) == 1, f"expected the terminal x only: {found}") + line = source.splitlines()[1] + terminal = line.rindex("x") + 1 + check(found[0]["use"]["line"] == 2 and found[0]["use"]["startByte"] == terminal, + f"wrong terminal token: {found[0]['use']} vs column {terminal}") + check(found[0]["definition"]["line"] == 1, found) + case(compiler, observer, "same-name qualifier", {"unit.cpp": source}, "unit.cpp", + verify=verify) + + +def declared_only_case(compiler, observer): + source = "int only(int);\nint use() { return only(1); }\n" + def verify(report, work): + found = by_name(report, "only") + check(len(found) == 1 and found[0]["definition"] is None, found) + case(compiler, observer, "declared only", {"unit.cpp": source}, "unit.cpp", + verify=verify) + + +def template_case(compiler, observer): + source = "template T twice(T value) { return value + value; }\nint q() { return twice(1); }\n" + def verify(report, work): + check(not by_name(report, "twice"), "template instantiation escaped the filter") + case(compiler, observer, "template instantiation", {"unit.cpp": source}, "unit.cpp", + verify=verify, partial=True) + + +def bom_case(compiler, observer): + source = "\ufeffint f() { return 1; } int q() { return f(); }\n" + def verify(report, work): + found = by_name(report, "f") + check(len(found) == 1, found) + expected = source.encode("utf-8").rindex(b"f()") + 1 + check(found[0]["use"]["startByte"] == expected, + f"BOM-shifted use {found[0]['use']} vs byte column {expected}") + case(compiler, observer, "UTF-8 BOM", {"unit.cpp": source}, "unit.cpp", verify=verify) + + +def space_case(compiler, observer): + source = "int spaced(int value) { return value; }\nint q() { return spaced(1); }\n" + with tempfile.TemporaryDirectory(prefix="vls-observer-") as temp: + work = Path(temp) / "left right" + work.mkdir() + path = work / "unit file.cpp" + path.write_text(source, encoding="utf-8") + nonce = secrets.token_hex(16) + manifest(work, nonce, [path.resolve()]) + result = compile(compiler, observer, work, path.resolve()) + check(result.returncode == 0, result.stderr[-800:]) + report = analyze(work, nonce, {path.resolve()}) + found = by_name(report, "spaced") + check(len(found) == 1 and found[0]["use"]["path"] == str(path.resolve()), found) + print("path with spaces: ok") + + +def capacity_case(compiler, observer): + calls = "\n".join(f" total += f({index});" for index in range(300)) + source = f"int f(int value) {{ return value; }}\nint q() {{\n int total = 0;\n{calls}\n return total;\n}}\n" + def verify(report, work): + check(report["reason"] == "capacity", report["reason"]) + check(report["occurrences"] == [], "partial facts published after capacity") + case(compiler, observer, "capacity", {"unit.cpp": source}, "unit.cpp", + complete=False, verify=verify) + + +def error_case(compiler, observer): + source = "int q() { return missing(1); }\n" + def verify(report, work): + check(report["reason"] == "compileErrors", report["reason"]) + check(report["occurrences"] == [], "facts published for a failed compile") + case(compiler, observer, "compile error", {"unit.cpp": source}, "unit.cpp", + status=1, complete=False, verify=verify) + recovered = "int missing(int value) { return value; }\nint q() { return missing(1); }\n" + def verify_recovered(report, work): + found = by_name(report, "missing") + check(len(found) == 1 and found[0]["definition"]["line"] == 1, found) + case(compiler, observer, "recovery", {"unit.cpp": recovered}, "unit.cpp", + verify=verify_recovered) + + +def malformed_case(compiler, observer): + source = "int f(int value) { return value; }\nint q() { return f(1); }\n" + for label, nonce, paths in ( + ("uppercase nonce", "A" * 32, None), + ("short nonce", "a" * 31, None), + ("relative path", "a" * 32, "unit.cpp"), + ("missing file", "a" * 32, "/nonexistent/vls-observer.cpp")): + with tempfile.TemporaryDirectory(prefix="vls-observer-") as temp: + work = Path(temp) + (work / "unit.cpp").write_text(source, encoding="utf-8") + selected = paths if paths is not None else str((work / "unit.cpp").resolve()) + (work / "inputs").write_text( + f"VLS-OCCURRENCES-1\n{nonce}\n{selected}\n", encoding="utf-8") + result = compile(compiler, observer, work, (work / "unit.cpp").resolve()) + check(result.returncode != 0, f"{label}: malformed manifest was accepted") + check(not (work / "report").exists(), f"{label}: report after a malformed manifest") + print("malformed manifests: ok") + + +def fixed_paths(compiler, observer): + """Consume a report from the fixed runtime paths inside a sealed view.""" + bwrap, store = shutil.which("bwrap"), shutil.which("nix-store") + if not bwrap or not store: + print("fixed runtime paths: skipped (bubblewrap or nix-store unavailable)") + return + frontend = Path(subprocess.check_output([compiler, "-print-prog-name=cc1plus"], + text=True).strip()).resolve(strict=True) + check(frontend.is_relative_to("/nix/store"), "expected a Nix GCC package") + roots = sorted({Path(*frontend.parts[:4]), Path(*compiler.parts[:4])}) + closure = sorted({Path(p) for root in roots + for p in subprocess.check_output([store, "-qR", str(root)], + text=True).splitlines()}) + check(0 < len(closure) <= 256, "unexpected compiler runtime closure") + with tempfile.TemporaryDirectory(prefix="vls-observer-fixed-") as temp: + work = Path(temp) + source = (work / "unit.cpp").resolve() + source.write_text("int f(int value) { return value; }\nint q() { return f(1); }\n", + encoding="utf-8") + nonce = secrets.token_hex(16) + inputs = (work / "inputs").resolve() + inputs.write_text(f"VLS-OCCURRENCES-1\n{nonce}\n{source}\n", encoding="utf-8") + output = work / "out" + output.mkdir() + sandbox = [bwrap, "--unshare-all", "--die-with-parent", "--new-session", "--clearenv", + "--setenv", "LC_ALL", "C", "--dev", "/dev", "--tmpfs", "/tmp"] + for path in closure: + sandbox += ["--ro-bind", str(path), str(path)] + sandbox += ["--dir", "/vls-observer", + "--bind", str(output.resolve()), "/vls-observer", + "--ro-bind", str(observer.resolve()), "/vls-observer/occurrences.so", + "--ro-bind", str(inputs), "/vls-observer/inputs", + "--ro-bind", str(source), str(source), + "--chdir", str(work), "--"] + result = subprocess.run([*sandbox, str(compiler), "-std=c++26", "-fsyntax-only", + "-fplugin=/vls-observer/occurrences.so", str(source)], + capture_output=True, text=True, timeout=120) + check(result.returncode == 0, f"sealed compile failed: {result.stderr[-800:]}") + report = strict_json((output / "report").read_bytes()) + check(report["nonce"] == nonce and report["complete"] and len(report["occurrences"]) == 1, + f"wrong sealed report: {report}") + occurrence = report["occurrences"][0] + read_span(occurrence["use"], "f", "sealed use") + read_span(occurrence["definition"], "f", "sealed definition") + print(f"fixed runtime paths: sealed report with {len(closure)} compiler runtime paths") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--observer", required=True, type=Path) + parser.add_argument("--cxx", default="g++") + options = parser.parse_args() + observer = options.observer.resolve(strict=True) + check(observer.is_file(), "observer artifact is not a file") + selected = compiler() + overload_case(selected, observer) + header_case(selected, observer) + macro_case(selected, observer) + line_directive_case(selected, observer) + qualifier_case(selected, observer) + declared_only_case(selected, observer) + template_case(selected, observer) + bom_case(selected, observer) + space_case(selected, observer) + capacity_case(selected, observer) + error_case(selected, observer) + malformed_case(selected, observer) + fixed_paths(selected, observer) + print(f"stock observer: all cases passed with {selected}") + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, subprocess.SubprocessError) as exc: + raise SystemExit(f"verify-stock-observer: {exc}") diff --git a/tests/corpus/modules/api.cppm b/tests/corpus/modules/api.cppm new file mode 100644 index 0000000..e0ff636 --- /dev/null +++ b/tests/corpus/modules/api.cppm @@ -0,0 +1,20 @@ +module; +#include "config/seed.hpp" + +export module corpus.topology:api; + +#if CORPUS_BIASED +import :detail; +#endif + +export namespace topology { +enum class State { +#if CORPUS_BIASED + Ready = CORPUS_SEED + context_bias(), +#else + Ready = CORPUS_SEED, +#endif +}; + +consteval auto ready_info() { return ^^State::Ready; } +} diff --git a/tests/corpus/modules/config/seed.hpp b/tests/corpus/modules/config/seed.hpp new file mode 100644 index 0000000..130a0c3 --- /dev/null +++ b/tests/corpus/modules/config/seed.hpp @@ -0,0 +1,3 @@ +#pragma once + +#include "value.hpp" diff --git a/tests/corpus/modules/config/value.hpp b/tests/corpus/modules/config/value.hpp new file mode 100644 index 0000000..64b1672 --- /dev/null +++ b/tests/corpus/modules/config/value.hpp @@ -0,0 +1,3 @@ +#pragma once + +#define CORPUS_SEED 17 diff --git a/tests/corpus/modules/cycle-a.cppm b/tests/corpus/modules/cycle-a.cppm new file mode 100644 index 0000000..70c006b --- /dev/null +++ b/tests/corpus/modules/cycle-a.cppm @@ -0,0 +1,2 @@ +export module corpus.cycle.a; +import corpus.cycle.b; diff --git a/tests/corpus/modules/cycle-b.cppm b/tests/corpus/modules/cycle-b.cppm new file mode 100644 index 0000000..8299160 --- /dev/null +++ b/tests/corpus/modules/cycle-b.cppm @@ -0,0 +1,2 @@ +export module corpus.cycle.b; +import corpus.cycle.a; diff --git a/tests/corpus/modules/detail.cppm b/tests/corpus/modules/detail.cppm new file mode 100644 index 0000000..492753e --- /dev/null +++ b/tests/corpus/modules/detail.cppm @@ -0,0 +1,7 @@ +module corpus.topology:detail; + +namespace topology { +constexpr int context_bias() { return 7; } + +int private_step(int value) { return value + context_bias(); } +} diff --git a/tests/corpus/modules/header-importer.cpp b/tests/corpus/modules/header-importer.cpp new file mode 100644 index 0000000..5d49e67 --- /dev/null +++ b/tests/corpus/modules/header-importer.cpp @@ -0,0 +1,13 @@ +#if CORPUS_QUOTED_HEADER +import "./include/vls-unit.hpp"; +#else +import ; +#endif + +#if CORPUS_CHECK_HEADER_MACRO && CORPUS_HEADER_IMPORTS_TOPOLOGY +import corpus.topology; +#endif + +static_assert(unit_value == EXPECT_HEADER, "wrong header unit selected"); + +int main() { return unit_value == EXPECT_HEADER ? 0 : 1; } diff --git a/tests/corpus/modules/implementation.cpp b/tests/corpus/modules/implementation.cpp new file mode 100644 index 0000000..b3decb8 --- /dev/null +++ b/tests/corpus/modules/implementation.cpp @@ -0,0 +1,8 @@ +module corpus.topology; +import :detail; + +namespace topology { +int implementation_value() { + return private_step(static_cast([:ready_info():])); +} +} diff --git a/tests/corpus/modules/importer.cpp b/tests/corpus/modules/importer.cpp new file mode 100644 index 0000000..96178c2 --- /dev/null +++ b/tests/corpus/modules/importer.cpp @@ -0,0 +1,8 @@ +import corpus.topology; + +static_assert(static_cast([:topology::ready_info():]) == EXPECT_READY, + "wrong reflected module value"); + +int main() { + return topology::implementation_value() == EXPECT_READY + 7 ? 0 : 1; +} diff --git a/tests/corpus/modules/include/vls-unit.hpp b/tests/corpus/modules/include/vls-unit.hpp new file mode 100644 index 0000000..08caec4 --- /dev/null +++ b/tests/corpus/modules/include/vls-unit.hpp @@ -0,0 +1,3 @@ +#define CORPUS_HEADER_IMPORTS_TOPOLOGY 1 + +inline constexpr int unit_value = 11; diff --git a/tests/corpus/modules/missing-provider.cpp b/tests/corpus/modules/missing-provider.cpp new file mode 100644 index 0000000..40cf595 --- /dev/null +++ b/tests/corpus/modules/missing-provider.cpp @@ -0,0 +1 @@ +import corpus.missing; diff --git a/tests/corpus/modules/private-fragment.cppm b/tests/corpus/modules/private-fragment.cppm new file mode 100644 index 0000000..6cf3e00 --- /dev/null +++ b/tests/corpus/modules/private-fragment.cppm @@ -0,0 +1,7 @@ +export module corpus.fragment; + +export int visible() { return 1; } + +module :private; + +int hidden() { return 2; } diff --git a/tests/corpus/modules/shadow/vls-unit.hpp b/tests/corpus/modules/shadow/vls-unit.hpp new file mode 100644 index 0000000..733991d --- /dev/null +++ b/tests/corpus/modules/shadow/vls-unit.hpp @@ -0,0 +1 @@ +inline constexpr int unit_value = 29; diff --git a/tests/corpus/modules/std-importer.cpp b/tests/corpus/modules/std-importer.cpp new file mode 100644 index 0000000..1490aea --- /dev/null +++ b/tests/corpus/modules/std-importer.cpp @@ -0,0 +1 @@ +import std; diff --git a/tests/corpus/modules/system-importer.cpp b/tests/corpus/modules/system-importer.cpp new file mode 100644 index 0000000..3306a0b --- /dev/null +++ b/tests/corpus/modules/system-importer.cpp @@ -0,0 +1,3 @@ +import ; + +static_assert(sizeof(size_t) == sizeof(decltype(sizeof(0)))); diff --git a/tests/corpus/modules/topology.cppm b/tests/corpus/modules/topology.cppm new file mode 100644 index 0000000..d91904b --- /dev/null +++ b/tests/corpus/modules/topology.cppm @@ -0,0 +1,6 @@ +export module corpus.topology; +export import :api; + +export namespace topology { +int implementation_value(); +} diff --git a/tests/corpus/modules/verify.py b/tests/corpus/modules/verify.py new file mode 100644 index 0000000..3ec8036 --- /dev/null +++ b/tests/corpus/modules/verify.py @@ -0,0 +1,580 @@ +"""Verify GCC 16 module scanning and compilation in isolated CMI caches.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile + + +FIXTURES = Path(__file__).resolve().parent +FLAGS = ("-std=c++26", "-freflection", "-fmodules", "-fdiagnostics-color=never") +PREPROCESS = ("-E", "-MD") +ALLOW_MISSING = ("-M", "-MG") +MODULE = "corpus.topology" +API = f"{MODULE}:api" +DETAIL = f"{MODULE}:detail" +HEADER = "vls-unit.hpp" +TEXT_INPUTS = ("config/seed.hpp", "config/value.hpp") +MODULE_UNITS = ("detail", "api", "topology", "implementation") +MAX_SCAN_BYTES = 256 * 1024 +MAX_MANIFEST_BYTES = 2 * 1024 * 1024 +COMPILER_ENV = ("LC_ALL", "GCC_EXEC_PREFIX", "COMPILER_PATH", "LIBRARY_PATH", + "NIX_CFLAGS_COMPILE", "NIX_CFLAGS_COMPILE_FOR_TARGET") + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def capture(stream): + stream.seek(0) + return read_limited(stream, 8192).decode("utf-8", errors="replace").strip() + + +def read_limited(stream, limit): + data = stream.read(limit + 1) + require(len(data) <= limit, f"{stream.name}: exceeded {limit} bytes") + return data + + +def scan_text(path): + with path.open("rb") as stream: + return read_limited(stream, MAX_SCAN_BYTES).decode("utf-8") + + +def digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True).encode("ascii")).hexdigest() + + +def file_digest(path, limit=MAX_SCAN_BYTES): + require(path.is_file(), f"expected a regular fixture input: {path}") + digest = hashlib.sha256() + with path.open("rb") as stream: + while chunk := stream.read(min(limit + 1, 1024 * 1024)): + require(len(chunk) <= limit, f"file exceeds hashing limit: {path}") + limit -= len(chunk) + digest.update(chunk) + return digest.hexdigest() + + +def rejection(result, diagnostic): + return {"exit": result.returncode, + "diagnostic": next(line for line in result.stderr.splitlines() if diagnostic in line)} + + +class Corpus: + def __init__(self, compiler, planner=None): + self.compiler = compiler + self.planner = planner + self.env = {**os.environ, "LC_ALL": "C"} + # GCC's default mapper keeps CMIs under the invocation's working directory. + for key in ("CXX_MODULE_MAPPER", "CPATH", "CPLUS_INCLUDE_PATH"): + self.env.pop(key, None) + self.scans = {} + self.rejections = {} + self.observations = {} + self.plans = {} + + def run(self, work, argv, diagnostic=None, *, stdin=subprocess.DEVNULL): + with tempfile.TemporaryFile(dir=work) as stdout, tempfile.TemporaryFile(dir=work) as stderr: + result = subprocess.run(argv, cwd=work, env=self.env, stdin=stdin, + stdout=stdout, stderr=stderr, timeout=30) + result.stdout, result.stderr = capture(stdout), capture(stderr) + expected = 0 if diagnostic is None else 1 + require(result.returncode == expected and (diagnostic is None or diagnostic in result.stderr), + f"{work.name}: {argv!r}: expected exit {expected}, diagnostic {diagnostic!r}; " + f"got exit {result.returncode}\n{result.stderr}\n{result.stdout}") + return result + + def compile(self, work, *args, diagnostic=None): + return self.run(work, [self.compiler, *FLAGS, *args], diagnostic) + + def reject(self, work, name, diagnostic, *args): + result = self.compile(work, *args, diagnostic=diagnostic) + self.rejections[f"{work.name}/{name}"] = {"arguments": args, **rejection(result, diagnostic)} + + def scan(self, work, name, source, *, provides=None, requires=(), flags=(), + mode=PREPROCESS, make_inputs=(), diagnostic=None, writes_rule=True): + output = f"scan-{name}.json" + depfile = f"scan-{name}.d" + primary = f"{name}.o" + make_target = f"{name}.make.o" + argv = [self.compiler, *FLAGS, *flags, *mode, "-MF", depfile, "-MT", make_target, + "-fdeps-format=p1689r5", f"-fdeps-file={output}", f"-fdeps-target={primary}", + "-o", os.devnull, source] + result = self.run(work, argv, diagnostic) + case = f"{work.name}/{name}" + require(case not in self.scans, f"duplicate scanner capture: {case}") + record = {"source": source, "options": [*mode, *flags], "exit": result.returncode} + if diagnostic is not None: + record.update(rejection(result, diagnostic)) + self.scans[case] = record + + path = work / output + require(path.is_file() == writes_rule, f"{case}: unexpected presence of P1689 output") + if not writes_rule: + record["rule"] = None + return + + raw = scan_text(path) + data = json.loads(raw) + require((data["version"], data["revision"], len(data["rules"])) == (0, 0, 1), + f"{case}: unexpected GCC P1689 envelope {data!r}") + rule = data["rules"][0] + observed_provides = rule.get("provides", []) + observed_requires = sorted(rule["requires"], key=lambda item: item["logical-name"]) + expected_provides = [] if provides is None else [ + {"logical-name": provides[0], "is-interface": provides[1]}, + ] + expected_requires = [{"logical-name": item} for item in sorted(requires)] + require((rule["primary-output"], observed_provides, observed_requires) == + (primary, expected_provides, expected_requires), f"{case}: unexpected P1689 rule {rule!r}") + record["rule"] = {"primary-output": rule["primary-output"], "provides": observed_provides, + "requires": observed_requires} + + tokens = scan_text(work / depfile).replace("\\\n", " ").split() + require(tokens and tokens[0] == f"{make_target}:" and set(make_inputs).issubset(tokens[1:]), + f"{case}: unexpected Make dependencies {tokens!r}") + if make_inputs: + record["make_inputs"] = list(make_inputs) + if self.planner: + self.observations[case] = (argv, raw, tokens[1:], len(self.scans)) + + def identify_toolchain(self, work, version, target): + frontend = Path(self.run(work, [self.compiler, "-print-prog-name=cc1plus"]).stdout) + require(frontend.is_absolute(), f"GCC did not identify its cc1plus: {frontend}") + images = (Path(self.compiler).resolve(strict=True), frontend.resolve(strict=True)) + self.toolchain = digest({ + "version": version, "target": target, + "images": [(str(path), file_digest(path, 512 * 1024 * 1024)) for path in images], + "environment": {key: self.env.get(key) for key in COMPILER_ENV}, + }) + + def member(self, work, name, *, owner=None, writer=None, dependencies=(), complete=True, + header_provider=False, no_header_units=True): + case = f"{work.name}/{name}" + record = self.scans[case] + argv, raw, make_dependencies, sequence = self.observations[case] + owner = owner or record["source"] + expected = {owner, *record.get("make_inputs", ()), *dependencies} + actual = set(make_dependencies) + implicit = actual - expected + # The only nonfixture input in these selected runs is GCC's implicit preinclude, + # when present. Refuse to open any other dependency named by the depfile. + require(expected <= actual and len(implicit) <= 1 and + all(Path(path).is_absolute() and Path(path).name == "stdc-predef.h" + for path in implicit), f"{case}: cannot attest dependencies {make_dependencies!r}") + observations = [(path, file_digest(work / path)) for path in make_dependencies] + primary = record["rule"]["primary-output"] + member = { + "name": name, "source": record["source"], "owning_source": owner, + "argv": argv, "exit": record["exit"], "p1689": raw, + "primary_output": primary, "writer": writer or primary, + "command_id": digest((self.toolchain, str(work), argv)), + "source_id": dict(observations)[owner], "textual_closure": digest(observations), + "complete": complete, "header_provider": header_provider, + "no_header_units": no_header_units, + } + return {**member, "scan_revision": digest((sequence, member))} + + def plan(self, work, name, requested, members, shared_flags): + # These are closed, authored fixture inputs. The only named topology lookups are + # the quoted config headers and the private CMI root. The reader assertion define + # belongs to its exact command, while the shared bias define belongs to the domain. + require(all(member["argv"][1:1 + len(FLAGS) + len(shared_flags)] == [*FLAGS, *shared_flags] + for member in members), "scan command does not match fixture domain") + compatibility = digest((self.toolchain, FLAGS, shared_flags)) + inputs = {member["name"]: {key: member[key] for key in + ("command_id", "source_id", "textual_closure", "exit")} + for member in members} + lookup = digest((str(work), str(work / "gcm.cache"), inputs)) + revision = digest((compatibility, lookup, [member["scan_revision"] for member in members])) + manifest = {"cwd": str(work), "revision": revision, "toolchain": self.toolchain, + "compatibility": compatibility, "lookup": lookup, "requested": requested, + "members": members} + payload = json.dumps(manifest).encode("ascii") + require(len(payload) <= MAX_MANIFEST_BYTES, "planner fixture manifest too large") + with tempfile.TemporaryFile(dir=work) as stdin: + stdin.write(payload) + stdin.seek(0) + result = self.run(work, [self.planner], stdin=stdin) + require(not result.stderr, f"planner wrote to stderr: {result.stderr}") + plan = json.loads(result.stdout) + require(isinstance(plan, dict) and plan.get("matches_census") is True, + f"{work.name}/{name}: planner lost census identity") + self.plans[f"{work.name}/{name}"] = { + **plan, "census_revision": revision, "compatibility": compatibility, + "lookup": lookup, "inputs": inputs, + } + return plan + + +def copy_fixtures(work): + for source in FIXTURES.rglob("*"): + if source.suffix in {".cpp", ".cppm", ".hpp"}: + destination = work / source.relative_to(FIXTURES) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + + +def run_reader(corpus, work, bias, expected, name): + corpus.compile(work, f"-DCORPUS_BIASED={bias}", f"-DEXPECT_READY={expected}", + "-c", "importer.cpp", "-o", f"{name}.o") + corpus.compile(work, *(f"{unit}.o" for unit in MODULE_UNITS), f"{name}.o", "-o", name) + result = corpus.run(work, [work / name]) + return {"reflected_value": expected, "implementation_value": expected + 7, "exit": result.returncode} + + +def require_blocked(plan, expected, label): + actual = {(entry["code"], entry.get("unit"), entry.get("scan_error")) for entry in plan["blockers"]} + require(plan["ready"] is False and plan["claims_complete"] is False and + plan["order"] == [] and actual == expected, + f"{label}: unexpected planner disposition {plan!r}") + + +def check_topology_plan(corpus, work, flags, bias, check_invalid_wire): + members = [corpus.member(work, name) for name in MODULE_UNITS] + importer = corpus.member(work, "importer", writer="reader.o") + plan = corpus.plan(work, "named", "importer", [*members, importer], flags) + expected_order = ["api", "topology", "importer"] + if bias: + expected_order.insert(0, "detail") + require(plan["ready"] is True and plan["claims_complete"] is True and + plan["order"] == expected_order and not plan["blockers"], + f"{work.name}: unexpected prerequisite order {plan!r}") + expected_units = { + "detail": {"kind": "internal_partition", + "consumers": ["api", "implementation"] if bias else ["implementation"]}, + "api": {"kind": "interface_partition", "consumers": ["topology"]}, + "topology": {"kind": "primary_interface", "consumers": ["implementation", "importer"]}, + "implementation": {"kind": "unknown", "consumers": []}, + "importer": {"kind": "unknown", "consumers": []}, + } + require(plan["units"] == expected_units, f"{work.name}: unexpected module reverse edges {plan!r}") + + if check_invalid_wire: + wrong_output = json.loads(importer["p1689"]) + wrong_output["rules"][0]["primary-output"] = "wrong-importer.o" + for error, raw in (("wrong_output", json.dumps(wrong_output)), + ("invalid_json", importer["p1689"].rstrip()[:-1])): + changed = {**importer, "p1689": raw, "scan_revision": digest((importer["scan_revision"], raw))} + plan = corpus.plan(work, error, "importer", [*members, changed], flags) + require_blocked(plan, {("invalid_rule", "importer", error)}, error) + + +def check_topology(corpus, work, seed, bias, previous_context=None): + copy_fixtures(work) + if seed != 17: + path = work / "config/value.hpp" + text = path.read_text(encoding="utf-8") + require(text.count("#define CORPUS_SEED 17\n") == 1, "unexpected saved seed fixture") + path.write_text(text.replace("#define CORPUS_SEED 17\n", f"#define CORPUS_SEED {seed}\n"), + encoding="utf-8") + + flags = (f"-DCORPUS_BIASED={bias}",) + corpus.scan(work, "detail", "detail.cppm", provides=(DETAIL, False), flags=flags) + corpus.scan(work, "api", "api.cppm", provides=(API, True), requires=(DETAIL,) if bias else (), + flags=flags, make_inputs=TEXT_INPUTS) + corpus.scan(work, "topology", "topology.cppm", provides=(MODULE, True), requires=(API,), flags=flags) + corpus.scan(work, "implementation", "implementation.cpp", requires=(MODULE, DETAIL), flags=flags) + expected = seed + 7 * bias + corpus.scan(work, "importer", "importer.cpp", requires=(MODULE,), + flags=(*flags, f"-DEXPECT_READY={expected}")) + cache = work / "gcm.cache" + require(not list(cache.rglob("*.gcm")), f"{work.name}: preprocessing created a CMI") + if corpus.planner: + check_topology_plan(corpus, work, flags, bias, check_invalid_wire=(seed == 17)) + + for unit in MODULE_UNITS: + suffix = "cpp" if unit == "implementation" else "cppm" + corpus.compile(work, *flags, "-c", f"{unit}.{suffix}", "-o", f"{unit}.o") + cmis = sorted(path.name for path in cache.glob("*.gcm")) + require(cmis == [f"{MODULE}-api.gcm", f"{MODULE}-detail.gcm", f"{MODULE}.gcm"], + f"{work.name}: unexpected named-module CMIs {cmis!r}") + reader = run_reader(corpus, work, bias, expected, "reader") + if previous_context is not None: + previous_bias, previous_value = previous_context + corpus.reject(work, "stale-expectation", "error: static assertion failed: wrong reflected module value", + f"-DCORPUS_BIASED={previous_bias}", f"-DEXPECT_READY={previous_value}", + "-fsyntax-only", "importer.cpp") + return {"seed": seed, "bias_flag": bias, "cmis": cmis, **reader} + + +def check_visibility(corpus, work): + corpus.reject(work, "hidden-partition-name", "error: 'context_bias' is not a member of 'topology'", + "-fsyntax-only", "visibility.cpp") + corpus.reject(work, "partition-import-in-global-module", "error: import specifying a module-partition", + "-DCORPUS_DIRECT_PARTITION=1", "-fsyntax-only", "visibility.cpp") + + +def header_reader(corpus, work, name, flags, value, logical_name, cmi): + executable = f"header-reader-{name}" + result = corpus.compile(work, *flags, f"-DEXPECT_HEADER={value}", "-flang-info-module-cmi", + "header-importer.cpp", "-o", executable) + require(f"{logical_name}: note: reading CMI '{cmi}'" in result.stderr, + f"{name}: wrong CMI read\n{result.stderr}") + result = corpus.run(work, [work / executable]) + return {"value": value, "cmi": cmi, "exit": result.returncode} + + +def check_header_units(corpus, work, system_header): + copy_fixtures(work) + normal = ("-Iinclude",) + shadow_first = ("-Ishadow", *normal) + quoted = ("-DCORPUS_QUOTED_HEADER=1", *shadow_first) + header_macro = "-DCORPUS_CHECK_HEADER_MACRO=1" + source = "header-importer.cpp" + normal_name, shadow_name = f"./include/{HEADER}", f"./shadow/{HEADER}" + normal_cmi, shadow_cmi = f"gcm.cache/,/include/{HEADER}.gcm", f"gcm.cache/,/shadow/{HEADER}.gcm" + system_cmi = f"gcm.cache/.{system_header}.gcm" + missing = "error: failed to read compiled module" + + corpus.scan(work, "unresolved-header", source, requires=(f"./{HEADER}",), + mode=ALLOW_MISSING, make_inputs=(HEADER,)) + corpus.scan(work, "cold-header", source, flags=normal, + diagnostic=f"{normal_name}: {missing}", writes_rule=False) + corpus.scan(work, "cold-header-macro", source, requires=(normal_name,), + flags=(*normal, header_macro), mode=ALLOW_MISSING) + corpus.scan(work, "header-provider", HEADER, provides=(normal_name, True), + flags=(*normal, "-x", "c++-user-header")) + corpus.compile(work, *normal, "-x", "c++-user-header", "-c", HEADER) + corpus.scan(work, "warm-header-macro", source, requires=(normal_name, MODULE), + flags=(*normal, header_macro), mode=ALLOW_MISSING) + if corpus.planner: + provider = corpus.member(work, "header-provider", owner=f"include/{HEADER}", + header_provider=True) + # GCC recorded a CMI prerequisite and found the macro-conditioned edge. The depfile + # cannot certify the consumed CMI generation against this provider's full source closure. + consumer = corpus.member(work, "warm-header-macro", dependencies=(normal_cmi,), + complete=False, no_header_units=False) + plan = corpus.plan(work, "warm-header-pending", "warm-header-macro", [provider, consumer], normal) + require_blocked(plan, {("incomplete_scan", "warm-header-macro", None), + ("unproven_mapping", "warm-header-macro", None)}, "warm header CMI") + + results = {} + for name, flags, value, logical_name, cmi in ( + ("normal", normal, 11, normal_name, normal_cmi), + ("quoted", quoted, 11, normal_name, normal_cmi), + ("shadow", shadow_first, 29, shadow_name, shadow_cmi), + ): + if name == "shadow": + corpus.reject(work, "different-header-lookup", f"{shadow_name}: {missing}", + *flags, "-DEXPECT_HEADER=29", "-fsyntax-only", source) + corpus.scan(work, "shadow-provider", HEADER, provides=(shadow_name, True), + flags=(*flags, "-x", "c++-user-header")) + corpus.compile(work, *flags, "-x", "c++-user-header", "-c", HEADER) + corpus.scan(work, f"{name}-header", source, requires=(logical_name,), flags=flags) + results[name] = header_reader(corpus, work, name, flags, value, logical_name, cmi) + + system_source = "system-importer.cpp" + corpus.scan(work, "cold-system-header", system_source, diagnostic=f"{system_header}: {missing}", + writes_rule=False) + corpus.scan(work, "system-header-missing-allowed", system_source, requires=(system_header,), + mode=ALLOW_MISSING) + corpus.scan(work, "system-header-provider", "stddef.h", provides=(system_header, True), + flags=("-x", "c++-system-header")) + corpus.compile(work, "-x", "c++-system-header", "-c", "stddef.h") + corpus.scan(work, "system-header", system_source, requires=(system_header,), mode=("-E", "-MMD")) + result = corpus.compile(work, "-flang-info-module-cmi", "-fsyntax-only", system_source) + require(f"{system_header}: note: reading CMI '{system_cmi}'" in result.stderr, + f"wrong system CMI read\n{result.stderr}") + results["system"] = {"cmi": system_cmi, "exit": result.returncode} + return results + + +def check_unresolved(corpus, work): + copy_fixtures(work) + missing = "error: failed to read compiled module" + for name, needed, provided in ( + ("missing-provider.cpp", "corpus.missing", None), + ("std-importer.cpp", "std", None), + ("cycle-a.cppm", "corpus.cycle.b", "corpus.cycle.a"), + ("cycle-b.cppm", "corpus.cycle.a", "corpus.cycle.b"), + ): + case = Path(name).stem + corpus.scan(work, case, name, provides=(provided, True) if provided else None, requires=(needed,)) + corpus.reject(work, case, f"{needed}: {missing}", "-c", name, "-o", f"{case}.o") + + fragment = "private-fragment.cppm" + corpus.scan(work, "private-fragment", fragment, provides=("corpus.fragment", True), + diagnostic="error: module already declared") + fragment_cmi = work / "gcm.cache/corpus.fragment.gcm" + require(not fragment_cmi.exists(), "private fragment scan created a CMI") + if corpus.planner: + member = corpus.member(work, "private-fragment", complete=False) + plan = corpus.plan(work, "failed-scan", "private-fragment", [member], ()) + require_blocked(plan, {("scan_failed", "private-fragment", None), + ("incomplete_scan", "private-fragment", None)}, "failed scan with rule") + diagnostic = "sorry, unimplemented: private module fragment" + result = corpus.compile(work, "-c", fragment, "-o", "private-fragment.o", diagnostic=diagnostic) + return {**rejection(result, diagnostic), "cmi_written_after_failure": fragment_cmi.is_file()} + + +def check_artifacts(compiler, work, fixture): + """Produce a real CMI through the C++ producer and consume the published copy.""" + root = work / "artifacts" + root.mkdir(parents=True, exist_ok=True) + source = root / "corpus.cmi.cppm" + source.write_text("export module corpus.cmi;\n" + "export int twice(int value) { return value * 2; }\n", encoding="utf-8") + command = [compiler, "-std=c++26", "-fmodules-ts", "-c", str(source), + "-o", str(root / "corpus.cmi.o")] + manifest = { + "staging": str(root / "staging"), + "cache": str(root / "cache"), + "compatibility": "gcc-corpus/x86_64", + "units": [{ + "alternative": "corpus.cmi", + "working_directory": str(root), + "command": command, + "command_id": "command-corpus-cmi", + "source_id": "source-corpus-cmi", + "textual_closure": "closure-corpus-cmi", + }], + } + result = subprocess.run([str(fixture)], input=json.dumps(manifest).encode(), + capture_output=True, timeout=120) + require(result.returncode == 0, + f"artifact fixture failed: {result.stderr[-800:].decode(errors='replace')!r}") + report = json.loads(result.stdout) + require(len(report.get("generation", "")) == 64 and len(report.get("artifacts", [])) == 1, + "incomplete generation report") + cmi = Path(report["artifacts"][0]["path"]) + require(cmi.is_file() and cmi.read_bytes()[:4] == b"\x7fELF", + "the published artifact is not a GCC CMI") + importer = root / "importer" + (importer / "gcm.cache").mkdir(parents=True) + published = importer / "gcm.cache" / "corpus.cmi.gcm" + shutil.copyfile(cmi, published) + (importer / "main.cpp").write_text( + "import corpus.cmi;\nint main() { return twice(21) == 42 ? 0 : 1; }\n", encoding="utf-8") + usable = subprocess.run([compiler, "-std=c++26", "-fmodules-ts", "-fsyntax-only", "main.cpp"], + cwd=importer, capture_output=True, timeout=120) + require(usable.returncode == 0, + f"the published CMI was not usable: {usable.stderr[-800:].decode(errors='replace')!r}") + published.write_bytes(published.read_bytes()[:128]) + broken = subprocess.run([compiler, "-std=c++26", "-fmodules-ts", "-fsyntax-only", "main.cpp"], + cwd=importer, capture_output=True, timeout=120) + require(broken.returncode != 0, "a truncated CMI was accepted") + scan_command = [compiler, *FLAGS, *PREPROCESS, "-MF", str(root / "scan.d"), + "-MT", "scan.o", "-fdeps-format=p1689r5", + f"-fdeps-file={root / 'scan-deps.json'}", + f"-fdeps-target={root / 'corpus.cmi.o'}", + "-o", os.devnull, str(source)] + scan_manifest = {"mode": "scan", "directory": str(root / "scan-private"), + "working_directory": str(root), "command": scan_command, + "output": {"working_directory": str(root), + "spelling": str(root / "corpus.cmi.o")}} + result = subprocess.run([str(fixture)], input=json.dumps(scan_manifest).encode(), + capture_output=True, timeout=120) + require(result.returncode == 0, + f"scan fixture failed: {result.stderr[-800:].decode(errors='replace')!r}") + scanned = json.loads(result.stdout) + require("corpus.cmi" in scanned["provides"], scanned) + require(scanned["requires"] == [], scanned) + require(len(scanned.get("generation", "")) == 64, + f"the scanned module did not publish an artifact generation: {scanned}") + supersede = dict(manifest) + supersede.update({"cache": str(root / "supersede-cache"), + "staging": str(root / "supersede-staging"), "supersede": True}) + result = subprocess.run([str(fixture)], input=json.dumps(supersede).encode(), + capture_output=True, timeout=120) + require(result.returncode == 0, + f"supersede fixture failed: {result.stderr[-800:].decode(errors='replace')!r}") + superseded = json.loads(result.stdout) + require(superseded.get("superseded") is True and superseded.get("published") is False, + f"a superseded module build published: {superseded}") + require(len(superseded.get("clean_generation", "")) == 64, + "the clean generation after supersession is missing") + return {"generation": report["generation"], "sha256": report["artifacts"][0]["sha256"], + "usable": True, "truncated_rejected": True, + "superseded_published": False, + "clean_generation": superseded["clean_generation"], + "scan": {"provides": scanned["provides"], "requires": scanned["requires"], + "generation": scanned["generation"]}} + + +def verify(compiler, work, planner=None, artifacts=None): + corpus = Corpus(compiler, planner) + version = corpus.run(work, [compiler, "-dumpfullversion"]).stdout + require(version.startswith("16."), f"expected GCC 16, got {version!r}") + target = corpus.run(work, [compiler, "-dumpmachine"]).stdout + system_header = corpus.run(work, [compiler, "-print-file-name=include/stddef.h"]).stdout + require(Path(system_header).is_absolute() and Path(system_header).is_file(), + f"GCC did not locate its system stddef.h: {system_header!r}") + if planner: + corpus.identify_toolchain(work, version, target) + + baseline = work / "baseline" + biased = work / "biased" + topologies = { + "baseline": check_topology(corpus, baseline, 17, 0), + "edited": check_topology(corpus, work / "edited", 41, 0, previous_context=(0, 17)), + "biased": check_topology(corpus, biased, 41, 1, previous_context=(0, 41)), + } + check_visibility(corpus, biased) + retained = run_reader(corpus, baseline, 0, 17, "retained-reader") + headers = check_header_units(corpus, work / "headers", system_header) + private_fragment = check_unresolved(corpus, work / "unresolved") + report = { + "gcc": version, "target": target, "flags": FLAGS, + "p1689": {"format": "p1689r5", "version": 0, "revision": 0, "scans": corpus.scans}, + "positive_controls": {"topologies": topologies, "retained_reader": retained, "header_units": headers}, + "expected_rejections": corpus.rejections, + "missing_capabilities": { + "private_module_fragment": private_fragment, + "complete_cold_header_unit_scan": { + "unresolved": "headers/unresolved-header", + "preprocess_error": "headers/cold-header", + "conditional_edge_missing": "headers/cold-header-macro", + "conditional_edge_present_with_cmi": "headers/warm-header-macro", + }, + }, + } + if planner: + original, edited, biased_plan = (corpus.plans[f"{name}/named"] for name in topologies) + old_api, new_api = original["inputs"]["api"], edited["inputs"]["api"] + require(old_api["source_id"] == new_api["source_id"] and + old_api["textual_closure"] != new_api["textual_closure"], + "the transitive header edit did not change the API input closure") + require(original["compatibility"] == edited["compatibility"] != biased_plan["compatibility"] and + len({plan["lookup"] for plan in (original, edited, biased_plan)}) == 3, + "fixture generations lost lookup or compatibility identity") + report["planner"] = {"toolchain": corpus.toolchain, "cases": corpus.plans} + if artifacts: + report["artifacts"] = check_artifacts(compiler, work, artifacts) + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cxx", default="g++", help="GCC 16 C++ executable") + parser.add_argument("--planner", type=Path, help="opt-in vls_module_scan_fixture executable") + parser.add_argument("--artifacts", type=Path, + help="opt-in vls_module_artifact_fixture executable") + args = parser.parse_args() + compiler = shutil.which(args.cxx) + if compiler is None: + parser.exit(1, f"GCC executable {args.cxx!r} was not found\n") + try: + planner = args.planner.resolve(strict=True) if args.planner else None + if planner is not None: + require(planner.is_file() and os.access(planner, os.X_OK), f"planner is not executable: {planner}") + artifacts = args.artifacts.resolve(strict=True) if args.artifacts else None + if artifacts is not None: + require(artifacts.is_file() and os.access(artifacts, os.X_OK), + f"artifact fixture is not executable: {artifacts}") + with tempfile.TemporaryDirectory(prefix="vls-gcc-modules-") as temp: + report = verify(os.path.abspath(compiler), Path(temp).resolve(), planner, artifacts) + print(json.dumps(report, indent=2)) + except (OSError, ValueError, subprocess.TimeoutExpired) as error: + parser.exit(1, f"{error}\n") + + +if __name__ == "__main__": + main() diff --git a/tests/corpus/modules/visibility.cpp b/tests/corpus/modules/visibility.cpp new file mode 100644 index 0000000..ba42260 --- /dev/null +++ b/tests/corpus/modules/visibility.cpp @@ -0,0 +1,6 @@ +#if CORPUS_DIRECT_PARTITION +import :detail; +#else +import corpus.topology; +static_assert(topology::context_bias() == 7); +#endif diff --git a/tests/debug/DapReplayTests.cpp b/tests/debug/DapReplayTests.cpp new file mode 100644 index 0000000..916d3e9 --- /dev/null +++ b/tests/debug/DapReplayTests.cpp @@ -0,0 +1,354 @@ +#include "Trace.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace protocol = Void::LanguageServer::Protocol; +using protocol::Json; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; +using namespace std::chrono_literals; +using namespace std::string_view_literals; + +std::filesystem::path adapter_executable() { +#ifdef VLS_DAP_EXECUTABLE + return VLS_DAP_EXECUTABLE; +#else + return std::filesystem::read_symlink("/proc/self/exe").parent_path() / "vls-dap"; +#endif +} + +const Json *member(const Json &value, std::string_view key) { + const auto *object = protocol::as_object(&value); + require(object != nullptr); + return protocol::find_member(*object, key); +} + +const Json &field(const Json &value, std::string_view key) { + const auto *entry = member(value, key); + require(entry != nullptr); + return *entry; +} + +const Json::Array &array(const Json &value, std::string_view key) { + const auto *entries = protocol::as_array(member(value, key)); + require(entries != nullptr); + return *entries; +} + +std::string_view text(const Json &value, std::string_view key) { + const auto *entry = protocol::as_string(member(value, key)); + require(entry != nullptr); + return *entry; +} + +std::int64_t integer(const Json &value, std::string_view key) { + const auto *entry = std::get_if(&field(value, key).value); + require(entry != nullptr); + return *entry; +} + +struct Request { + std::string_view command; + std::string_view arguments{"{}"}; +}; + +constexpr Request initialize{"initialize", R"({"adapterID":"vls"})"}; +constexpr Request continue_thread{"continue", R"({"threadId":1})"}; +constexpr Request stack_trace{"stackTrace", R"({"threadId":1})"}; + +struct Transcript { + std::vector messages; + + const Json &response(int sequence, std::string_view command, bool success = true) const { + const auto matches = [sequence](const Json &message) { + return text(message, "type") == "response" && + integer(message, "request_seq") == sequence; + }; + const auto found = std::ranges::find_if(messages, matches); + require(found != messages.end()); + expect_eq(std::ranges::count_if(messages, matches), std::ptrdiff_t{1}); + expect_eq(text(*found, "command"), command); + expect(protocol::as_bool(member(*found, "success")) == success); + return *found; + } + + std::vector events(std::string_view name) const { + std::vector result; + for (const auto &message : messages) { + if (text(message, "type") == "event" && text(message, "event") == name) + result.push_back(&message); + } + return result; + } +}; + +Transcript +run(std::initializer_list requests, + const std::filesystem::path &fixture = std::filesystem::path{__FILE__}.parent_path() / + "fixtures" / "integral-17.vls", + std::size_t output_limit = 128 * 1024) { + std::ostringstream input; + int client_sequence = 0; + for (const auto &request : requests) { + const auto body = + std::format(R"({{"seq":{},"type":"request","command":"{}","arguments":{}}})", + ++client_sequence, request.command, request.arguments); + require(protocol::write_frame(input, body).has_value()); + } + + require(fixture.is_absolute()); + Void::Process::SpawnOptions options; + options.executable = adapter_executable(); + require(options.executable.is_absolute()); + options.arguments = {"--replay", fixture.string()}; + options.search_path = false; + options.environment.mode = Void::Process::EnvMode::explicit_only; + options.environment.set_vars = {{"LC_ALL", "C"}, {"PATH", ""}}; + options.kill_grace = 100ms; + auto child = Void::Process::spawn(options); + require(child.has_value()); + + Void::Process::CaptureLimits limits; + limits.max_stdin_bytes = 8192; + limits.max_stdout_bytes = output_limit; + limits.max_line_bytes = output_limit; + limits.max_stderr_bytes = 8192; + const auto output = Void::Process::communicate_blocking(*child, input.str(), limits, 4s); + require(output.has_value()); + require(!output->timed_out && !output->cancelled && !output->overflowed); + require(output->status.exited); + expect_eq(output->status.code, 0); + expect_eq(output->err, std::string{}); + + Transcript transcript; + std::istringstream replies{output->out}; + std::int64_t adapter_sequence = 0; + for (;;) { + const auto frame = protocol::read_frame(replies, {.body_bytes = limits.max_stdout_bytes}); + require(frame.has_value()); + if (!*frame) + break; + auto message = protocol::parse_json(**frame); + require(message.has_value()); + expect_eq(integer(*message, "seq"), ++adapter_sequence); + const auto type = text(*message, "type"); + require(type == "event" || type == "response"); + if (type == "response") { + const auto request_sequence = integer(*message, "request_seq"); + expect(request_sequence >= 1 && request_sequence <= client_sequence); + } else { + expect(text(*message, "event") != "exited"); + } + transcript.messages.push_back(std::move(*message)); + } + return transcript; +} + +void write_manifest(const std::filesystem::path &path, std::string_view source) { + auto trace = + vls::gcc::Trace::create(path, source, std::string(64, 'a'), std::string(32, 'b'), 1234); + require(trace.has_value()); +} + +void expect_before(const Json &first, const Json &second) { + expect(integer(first, "seq") < integer(second, "seq")); +} + +void expect_stack(const Json &reply, std::initializer_list names) { + const auto &frames = array(field(reply, "body"), "stackFrames"); + require(frames.size() == names.size()); + auto name = names.begin(); + for (const auto &frame : frames) { + expect_eq(text(frame, "name"), *name++); + expect(integer(frame, "id") > 0); + expect(member(frame, "source") == nullptr); + expect_eq(integer(frame, "line"), std::int64_t{0}); + expect_eq(integer(frame, "column"), std::int64_t{0}); + } +} + +} // namespace + +VOID_TEST(DapReplay, deferred_launch_finishes_after_configuration_done) { + const auto dap = + run({initialize, + {"launch"}, + {"setBreakpoints", + R"({"source":{"name":"input.cpp"},"breakpoints":[{"line":5},{"line":10}]})"}, + {"setExceptionBreakpoints", R"({"filters":[]})"}, + {"configurationDone"}, + {"threads"}, + stack_trace, + continue_thread, + stack_trace, + {"disconnect"}}); + + const auto &init = dap.response(1, "initialize"); + const auto initialized = dap.events("initialized"); + require(initialized.size() == 1); + expect_eq(integer(init, "seq"), std::int64_t{1}); + expect_before(init, *initialized.front()); + const auto &capabilities = field(init, "body"); + for (const auto name : {"supportsConfigurationDoneRequest", "supportsLoadedSourcesRequest", + "supportsTerminateRequest"}) { + expect(protocol::as_bool(member(capabilities, name)) == true); + } + for (const auto name : {"supportsStepBack", "supportsSteppingGranularity", + "supportsRestartFrame", "supportsDisassembleRequest"}) { + expect(protocol::as_bool(member(capabilities, name)) != true); + } + + const auto &breakpoint_reply = dap.response(3, "setBreakpoints"); + const auto &breakpoints = array(field(breakpoint_reply, "body"), "breakpoints"); + require(breakpoints.size() == 2); + for (const auto &breakpoint : breakpoints) + expect(protocol::as_bool(member(breakpoint, "verified")) == false); + dap.response(4, "setExceptionBreakpoints"); + + const auto &configured = dap.response(5, "configurationDone"); + const auto &launch = dap.response(2, "launch"); + const auto stopped = dap.events("stopped"); + require(stopped.size() == 2); + expect_before(*initialized.front(), configured); + expect_before(configured, launch); + expect_before(launch, *stopped[0]); + expect_before(dap.response(8, "continue"), *stopped[1]); + for (const auto *stop : stopped) { + const auto &body = field(*stop, "body"); + expect_eq(integer(body, "threadId"), std::int64_t{1}); + expect(!text(body, "reason").empty()); + } + + const auto &threads = array(field(dap.response(6, "threads"), "body"), "threads"); + require(threads.size() == 1); + expect_eq(integer(threads.front(), "id"), std::int64_t{1}); + expect_stack(dap.response(7, "stackTrace"), {"reflected_value", "twice"}); + expect_stack(dap.response(9, "stackTrace"), {"twice"}); + dap.response(10, "disconnect"); +} + +VOID_TEST(DapReplay, configuration_done_can_precede_launch_and_terminate) { + const auto dap = + run({initialize, {"configurationDone"}, {"launch"}, {"terminate"}, {"disconnect"}}); + const auto &configured = dap.response(2, "configurationDone"); + const auto &launch = dap.response(3, "launch"); + const auto stopped = dap.events("stopped"); + const auto terminated = dap.events("terminated"); + require(stopped.size() == 1); + require(terminated.size() == 1); + expect_before(configured, launch); + expect_before(launch, *stopped.front()); + expect_before(*stopped.front(), dap.response(4, "terminate")); + expect_before(dap.response(4, "terminate"), *terminated.front()); + dap.response(5, "disconnect"); +} + +VOID_TEST(DapReplay, disconnect_settles_a_deferred_launch) { + const auto dap = run({initialize, {"launch"}, {"disconnect"}}); + dap.response(1, "initialize"); + dap.response(2, "launch", false); + dap.response(3, "disconnect"); + expect(dap.events("stopped").empty()); +} + +VOID_TEST(DapReplay, one_session_identity_has_one_cursor_and_finishes_once) { + using vls::debug::ReplaySession; + static_assert(!std::is_copy_constructible_v); + static_assert(!std::is_copy_assignable_v); + const auto recording = + std::filesystem::path{__FILE__}.parent_path() / "fixtures" / "integral-17.vls"; + auto opened = ReplaySession::open(recording); + require(opened.has_value()); + auto session = std::move(*opened); + require(session.seek(6).has_value()); + const auto stopped = session.identity(); + session.finish(); + const auto done = session.identity(); + expect(!session.matches(stopped)); + expect(!session.seek(10)); + expect(!session.move_to_value(true)); + expect(!session.initial_position()); + expect(!session.paused()); + session.finish(); + expect(session.matches(done)); +} + +VOID_TEST(DapReplay, binary_source_keeps_its_digest_and_has_no_text_reference) { + Void::FileSystem::TempDir dir{"vls_dap_source_"}; + const auto path = dir / "binary.vls"; + write_manifest(path, "a\0\xffz"sv); + const auto dap = run({initialize, + {"launch"}, + {"configurationDone"}, + {"vls/session"}, + {"loadedSources"}, + {"source", R"({"sourceReference":1})"}, + {"disconnect"}}, + path); + const auto &state = field(dap.response(4, "vls/session"), "body"); + expect(protocol::as_bool(member(state, "sourceAvailable")) == false); + expect_eq(integer(state, "sourceByteLength"), std::int64_t{4}); + expect_eq(text(state, "sourceSha256").size(), std::size_t{64}); + expect(member(state, "sourceReference") == nullptr); + expect(array(field(dap.response(5, "loadedSources"), "body"), "sources").empty()); + dap.response(6, "source", false); + expect(dap.events("stopped").empty()); +} + +VOID_TEST(DapReplay, full_size_control_filled_source_round_trips_as_exact_text) { + Void::FileSystem::TempDir dir{"vls_dap_source_"}; + const auto path = dir / "controls.vls"; + std::string source(1024 * 1024, '\0'); + source.back() = '\x1f'; + write_manifest(path, source); + const auto dap = run({initialize, + {"configurationDone"}, + {"launch"}, + {"source", R"({"sourceReference":1})"}, + {"disconnect"}}, + path, 8 * 1024 * 1024); + const auto &body = field(dap.response(4, "source"), "body"); + expect(text(body, "content") == source); + expect(dap.events("stopped").empty()); +} + +VOID_TEST(DapReplay, unsupported_or_unreachable_controls_fail_without_moving) { + const auto dap = run({initialize, + continue_thread, + {"launch"}, + {"configurationDone"}, + {"next", R"({"threadId":1})"}, + {"stepBack", R"({"threadId":1})"}, + {"continue", R"({"threadId":2})"}, + stack_trace, + {"disconnect"}}); + dap.response(2, "continue", false); + dap.response(3, "launch"); + dap.response(4, "configurationDone"); + dap.response(5, "next", false); + dap.response(6, "stepBack", false); + dap.response(7, "continue", false); + expect_stack(dap.response(8, "stackTrace"), {"reflected_value", "twice"}); + dap.response(9, "disconnect"); + expect(dap.events("stopped").size() == 1); +} diff --git a/tests/debug/LiveDapTests.cpp b/tests/debug/LiveDapTests.cpp new file mode 100644 index 0000000..6124e5f --- /dev/null +++ b/tests/debug/LiveDapTests.cpp @@ -0,0 +1,199 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +namespace P = Void::LanguageServer::Protocol; +using Json = P::Json; +using Void::Testing::expect; +using Void::Testing::require; +using namespace std::chrono_literals; + +fs::path sibling(std::string_view name) { + const auto directory = fs::canonical("/proc/self/exe").parent_path(); + // VBS keeps every executable in one directory; CMake puts the server tools + // at the build root and the test executables under tests/. + if (fs::exists(directory / name)) + return directory / name; + return directory.parent_path() / name; +} + +void write_frame(int fd, const Json &message) { + auto body = P::serialize_json(message); + require(body.has_value()); + const std::string header = "Content-Length: " + std::to_string(body->size()) + "\r\n\r\n"; + for (const std::string_view part : {std::string_view{header}, std::string_view{*body}}) { + std::size_t done{}; + while (done != part.size()) { + const auto written = ::write(fd, part.data() + done, part.size() - done); + require(written > 0); + done += static_cast(written); + } + } +} + +std::optional read_frame(int fd, std::string &buffer) { + const auto deadline = std::chrono::steady_clock::now() + 20s; + while (true) { + const auto header = buffer.find("\r\n\r\n"); + if (header != std::string::npos) { + const auto marker = buffer.find("Content-Length: "); + require(marker != std::string::npos); + const auto length = std::stoul(buffer.substr(marker + 16)); + if (buffer.size() >= header + 4 + length) { + const auto body = buffer.substr(header + 4, length); + buffer.erase(0, header + 4 + length); + auto parsed = P::parse_json(body, 8); + require(parsed.has_value()); + return *parsed; + } + } + if (std::chrono::steady_clock::now() >= deadline) + return std::nullopt; + pollfd pipe{fd, POLLIN, 0}; + if (::poll(&pipe, 1, 100) <= 0) + continue; + char bytes[8192]; + const auto read = ::read(fd, bytes, sizeof bytes); + if (read <= 0) + return std::nullopt; + buffer.append(bytes, static_cast(read)); + } +} + +Json wait_response(int fd, std::string &buffer, std::int64_t sequence) { + while (true) { + auto message = read_frame(fd, buffer); + require(message.has_value()); + const auto *fields = P::as_object(&*message); + require(fields); + const auto *type = P::as_string(P::find_member(*fields, "type")); + const auto *request = P::find_member(*fields, "request_seq"); + if (type && *type == "response" && request) + if (const auto *value = std::get_if(&request->value); + value && *value == sequence) + return *message; + } +} + +Json wait_event(int fd, std::string &buffer, std::string_view name) { + while (true) { + auto message = read_frame(fd, buffer); + require(message.has_value()); + const auto *fields = P::as_object(&*message); + require(fields); + const auto *type = P::as_string(P::find_member(*fields, "type")); + const auto *event = P::as_string(P::find_member(*fields, "event")); + if (type && event && *type == "event" && *event == name) + return *message; + } +} +} // namespace + +VOID_TEST(LiveDap, breakpoints_and_typed_inspection_over_the_adapter) { + Void::FileSystem::TempDir temp{"vls_live_dap_"}; + const auto source = temp.path() / "normal.cpp"; + std::ofstream{source} << "int value = 17;\n"; + const auto trace = temp.path() / "session.vls"; + Void::Process::SpawnOptions spawn; + spawn.executable = sibling("vls-dap"); + spawn.arguments = {"--live", sibling("vls_live_worker_fixture").native(), + "/private/cc1plus", std::string(64, 'a'), + source.native(), trace.native()}; + spawn.search_path = false; + auto child = Void::Process::spawn(spawn); + require(child.has_value()); + const int input = child->stdin_fd(), output = child->stdout_fd(); + std::string buffer; + std::int64_t sequence{}; + auto request = [&](std::string_view command, Json::Object arguments) { + write_frame(input, Json{Json::Object{{"seq", Json{++sequence}}, + {"type", Json{std::string{"request"}}}, + {"command", Json{std::string{command}}}, + {"arguments", Json{std::move(arguments)}}}}); + return sequence; + }; + const auto object_of = [](const Json &value) { + const auto *fields = P::as_object(&value); + require(fields != nullptr); + return fields; + }; + const auto bool_of = [](const Json &value, std::string_view name) { + const auto *fields = P::as_object(&value); + require(fields != nullptr); + return P::as_bool(P::find_member(*fields, name)).value_or(false); + }; + request("initialize", {{"adapterID", Json{std::string{"vls"}}}}); + expect(bool_of(wait_response(output, buffer, sequence), "success")); + wait_event(output, buffer, "initialized"); + request("launch", {}); + request("configurationDone", {}); + wait_event(output, buffer, "stopped"); + + // Typed value projection from the live inspection snapshot. The reply + // objects must outlive the pointers into them, so each is kept in a local. + request("stackTrace", {{"threadId", Json{std::int64_t{1}}}}); + const Json stack_reply = wait_response(output, buffer, sequence); + const auto *stack_body = P::as_object(P::find_member(*object_of(stack_reply), "body")); + require(stack_body); + const auto *frames = P::as_array(P::find_member(*stack_body, "stackFrames")); + require(frames && !frames->empty()); + const auto *frame = P::as_object(&frames->front()); + require(frame); + const auto *handle = P::find_member(*frame, "id"); + require(handle); + request("scopes", {{"frameId", *handle}}); + const Json scopes_reply = wait_response(output, buffer, sequence); + const auto *scopes_body = P::as_object(P::find_member(*object_of(scopes_reply), "body")); + require(scopes_body); + const auto *scope_list = P::as_array(P::find_member(*scopes_body, "scopes")); + require(scope_list && !scope_list->empty()); + const auto *scope = P::as_object(&scope_list->front()); + require(scope); + const auto *reference = P::find_member(*scope, "variablesReference"); + require(reference); + request("variables", {{"variablesReference", *reference}}); + const Json values_reply = wait_response(output, buffer, sequence); + const auto *values_body = P::as_object(P::find_member(*object_of(values_reply), "body")); + require(values_body); + const auto *variables = P::as_array(P::find_member(*values_body, "variables")); + require(variables); + bool projected{}, reflected{}; + for (const auto &value : *variables) { + const auto *fields = P::as_object(&value); + const auto *name = fields ? P::as_string(P::find_member(*fields, "name")) : nullptr; + const auto *text = fields ? P::as_string(P::find_member(*fields, "value")) : nullptr; + if (name && text && *name == "Result" && *text == "17") + projected = true; + if (name && text && *name == "Ready" && text->find("input.cpp:1:20") != std::string::npos && + text->find("input.cpp:4:31") != std::string::npos) + reflected = true; + } + expect(projected); + expect(reflected); + + // Detailed frame, breakpoint and typed-value projection is covered by the + // real DAP transcript in tests/native/LiveDap.py; this suite registers the + // live control path in the C++ build. + request("continue", {{"threadId", Json{std::int64_t{1}}}}); + wait_response(output, buffer, sequence); + wait_event(output, buffer, "terminated"); + request("disconnect", {}); + wait_response(output, buffer, sequence); + static_cast(child->terminate(1s)); +} diff --git a/tests/debug/LiveSessionTests.cpp b/tests/debug/LiveSessionTests.cpp new file mode 100644 index 0000000..a7631c4 --- /dev/null +++ b/tests/debug/LiveSessionTests.cpp @@ -0,0 +1,112 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +// A worker may exit while the session still owns its stdin pipe. +struct IgnoreSigpipe { + IgnoreSigpipe() { std::signal(SIGPIPE, SIG_IGN); } +} ignore_sigpipe; +using namespace vls::debug::live; +using namespace std::chrono_literals; +using Void::Testing::expect; +using Void::Testing::require; + +struct Fixture { + Void::FileSystem::TempDir temp{"vls_live_session_"}; + fs::path source; + fs::path trace; + Options options; + + explicit Fixture(std::string name = "normal.cpp", std::chrono::milliseconds deadline = 5s) { + source = temp.path() / name; + std::ofstream{source} << "int value = 17;\n"; + trace = temp.path() / "session.vls"; + const auto worker = + fs::canonical("/proc/self/exe").parent_path() / "vls_live_worker_fixture"; + options = Options{worker, "/private/cc1plus", std::string(64, 'a'), source, trace, true, + deadline, 64 * 1024}; + } +}; +} // namespace + +VOID_TEST(LiveSession, steps_through_stops_and_inspects_each_generation) { + Fixture fixture; + LiveSession session{fixture.options}; + const auto first = session.start(); + if (!first.has_value()) + std::cerr << "start error: " << first.error() << '\n'; + require(first.has_value()); + expect(first->generation == 1 && first->sequence == 1); + expect(session.state() == State::stopped); + const auto first_snapshot = session.inspect(); + require(first_snapshot.has_value()); + const auto first_json = Void::LanguageServer::Protocol::serialize_json(*first_snapshot); + require(first_json.has_value()); + expect(first_json->find("\"17\"") != std::string::npos); + const auto second = session.step(); + require(second.has_value() && second->has_value()); + expect((*second)->generation == 2 && (*second)->sequence == 2); + const auto second_snapshot = session.inspect(); + require(second_snapshot.has_value()); + const auto second_json = Void::LanguageServer::Protocol::serialize_json(*second_snapshot); + require(second_json.has_value()); + expect(second_json->find("\"34\"") != std::string::npos); + require(session.step().has_value()); + const auto done = session.step(); + require(done.has_value()); + expect(!done->has_value()); + expect(session.state() == State::completed && session.outcome() == "completed"); +} + +VOID_TEST(LiveSession, continue_finishes_the_session) { + Fixture fixture; + LiveSession session{fixture.options}; + require(session.start().has_value()); + const auto done = session.continue_run(); + require(done.has_value()); + expect(!done->has_value() && session.state() == State::completed); + expect(session.stop() == std::nullopt); +} + +VOID_TEST(LiveSession, cancel_terminates_at_a_stop) { + Fixture fixture; + LiveSession session{fixture.options}; + require(session.start().has_value()); + require(session.cancel().has_value()); + expect(session.state() == State::cancelled); +} + +VOID_TEST(LiveSession, refuses_movement_without_a_stop) { + Fixture fixture; + LiveSession session{fixture.options}; + expect(!session.step().has_value()); + expect(!session.inspect().has_value()); + expect(!session.cancel().has_value()); +} + +VOID_TEST(LiveSession, rejects_malformed_worker_output) { + Fixture fixture{"malformed.cpp"}; + LiveSession session{fixture.options}; + const auto started = session.start(); + require(!started.has_value()); + expect(started.error().contains("bound") || started.error().contains("JSON")); +} + +VOID_TEST(LiveSession, enforces_the_notice_deadline) { + Fixture fixture{"silent.cpp", 200ms}; + LiveSession session{fixture.options}; + const auto started = session.start(); + require(!started.has_value()); + expect(started.error().contains("deadline")); +} diff --git a/tests/debug/LiveWorkerFixture.cpp b/tests/debug/LiveWorkerFixture.cpp new file mode 100644 index 0000000..f8f9114 --- /dev/null +++ b/tests/debug/LiveWorkerFixture.cpp @@ -0,0 +1,79 @@ +// Scripted private-compiler worker for the LiveSession suite. It speaks the +// same notice/control protocol as vls_gcc_probe without running a compiler. +#include +#include +#include +#include +#include +#include + +namespace { +constexpr std::string_view nonce = "0123456789abcdef0123456789abcdef"; + +void notice(const std::string &line) { std::cout << line << '\n' << std::flush; } + +void stopped(unsigned sequence) { + notice(R"({"kind":"stopped","nonce":")" + std::string{nonce} + R"(","stop":)" + + std::to_string(sequence) + "}"); +} + +void finished(std::string_view outcome) { + notice(R"({"kind":"finished","nonce":")" + std::string{nonce} + R"(","outcome":")" + + std::string{outcome} + R"(","exitCode":0,"reason":""})"); +} +} // namespace + +int main(int argc, char **argv) { + if (argc < 6 || std::string_view(argv[1]) != "run") + return 2; + const std::string scenario = std::filesystem::path(argv[4]).filename().string(); + notice(R"({"kind":"started","nonce":")" + std::string{nonce} + R"(","pid":1})"); + if (scenario == "silent.cpp") { + std::this_thread::sleep_for(std::chrono::seconds(60)); + return 0; + } + if (scenario == "malformed.cpp") { + std::cout << std::string(70000, 'x') << '\n' << std::flush; + return 0; + } + unsigned sequence = 1; + stopped(sequence); + std::string line; + while (std::getline(std::cin, line)) { + std::istringstream fields{line}; + std::string received, action; + unsigned requested = 0; + fields >> received >> requested >> action; + if (received != nonce) { + notice(R"({"kind":"rejected"})"); + continue; + } + if (action == "inspect") { + notice( + R"({"kind":"inspection","snapshot":{"schemaVersion":1,"sessionId":"live-fixture","generation":)" + + std::to_string(requested) + R"(,"eventSequence":)" + std::to_string(requested) + + R"(,"frames":[{"name":")" + + std::string(requested == 1 ? "reflected_value" + : requested == 2 ? "twice" + : "twice") + + R"(","line":)" + std::to_string(requested) + + R"(,"source":"input.cpp","depth":0,"cached":false}],"values":[{"name":"Result","value":")" + + std::to_string(requested * 17) + + R"("}],"origins":[{"source":"input.cpp","line":4,"byteColumn":31,"targetKind":"declaration","targetName":"Ready","targetSource":"input.cpp","targetLine":1,"targetByteColumn":20}]}})"); + } else if (action == "step") { + if (sequence < 3) { + stopped(++sequence); + } else { + finished("completed"); + return 0; + } + } else if (action == "continue") { + finished("completed"); + return 0; + } else if (action == "cancel") { + finished("cancelled"); + return 125; + } + } + return 0; +} diff --git a/tests/debug/RecordingTests.cpp b/tests/debug/RecordingTests.cpp new file mode 100644 index 0000000..0287bac --- /dev/null +++ b/tests/debug/RecordingTests.cpp @@ -0,0 +1,506 @@ +#include "../../experiments/frontend/gcc-worker/Trace.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace fs = std::filesystem; +namespace protocol = Void::LanguageServer::Protocol; +using protocol::Json; +using vls::gcc::ReplayRecording; +using vls::gcc::ReplayValuePoint; +using vls::gcc::Trace; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; +using namespace std::string_view_literals; + +constexpr auto nonce = "00112233445566778899aabbccddeeff"sv; +constexpr auto digest = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"sv; +constexpr std::int64_t pid = 4321; + +template +T checked(std::expected result, + std::source_location at = std::source_location::current()) { + expect_eq(result ? ""sv : std::string_view{result.error()}, ""sv, at); + require(result.has_value(), at); + return *std::move(result); +} + +std::string wire(std::uint32_t seq, std::string_view kind, std::string_view fields = {}) { + return std::format(R"({{"v":1,"nonce":"{}","seq":{},"kind":"{}"{}}})", nonce, seq, kind, + fields); +} + +struct Writer { + explicit Writer(const fs::path &path, std::string_view source = "int answer = 17;\n") + : trace(checked(Trace::create(path, source, digest, nonce, pid))) {} + + void event(std::string_view kind, std::string_view fields = {}) { + checked(trace->event(wire(sequence++, kind, fields))); + } + + void hello() { + event( + "hello", + R"(,"backend":"gcc-16.2.0/vls-eval-1","pid":4321,"capabilities":["integralReturn","cooperativeStep"],"kinds":["hello","enter","body","value","cached","stopped","resumed","leave","terminal","frontendEnd"])"); + } + + void frame(std::string_view kind, std::uint32_t id, std::optional parent, + std::string_view fields = {}) { + event(kind, std::format(R"(,"frame":{},"parent":{}{})", id, + parent ? std::to_string(*parent) : "null", fields)); + } + + void enter(std::optional parent, std::string_view name) { + frame( + "enter", sequence, parent, + std::format( + R"(,"name":"{}","sourceKind":"logicalDeclaration","source":"input.cpp","line":5,"byteColumn":17)", + name)); + } + + void integer(std::uint32_t id, std::optional parent, unsigned value) { + frame( + "value", id, parent, + std::format( + R"(,"value":{{"kind":"integer","precision":32,"signed":true,"bitsHex":"{:08x}"}})", + value)); + } + + void inner_stop(unsigned value) { + hello(); + enter({}, "twice"); + frame("body", 1, {}); + enter(1, "reflected_value"); + frame("body", 3, 1); + integer(3, 1, value); + frame("stopped", 3, 1); + } + + void outer_stop(unsigned value) { + checked(trace->authorize(6, "step")); + frame("resumed", 3, 1, R"(,"stop":6,"action":"step")"); + frame("leave", 3, 1, R"(,"outcome":"returned")"); + integer(1, {}, value); + frame("stopped", 1, {}); + } + + void finish_pair(std::string_view action = "continue") { + checked(trace->authorize(10, action)); + frame("resumed", 1, {}, std::format(R"(,"stop":10,"action":"{}")", action)); + frame("leave", 1, {}, R"(,"outcome":"returned")"); + event("frontendEnd"); + checked(trace->finish("completed", 0, "")); + } + + std::unique_ptr trace; + std::uint32_t sequence{}; +}; + +void write_pair(const fs::path &path, unsigned inner, std::string_view action = "continue") { + Writer writer{path, std::format("int answer = {};\n", inner)}; + writer.inner_stop(inner); + writer.outer_stop(inner * 2); + writer.finish_pair(action); +} + +const Json *member(const Json &json, std::string_view key) { + const auto *object = protocol::as_object(&json); + return object ? protocol::find_member(*object, key) : nullptr; +} + +const Json &field(const Json &json, std::string_view key) { + const auto *value = member(json, key); + require(value != nullptr); + return *value; +} + +std::string_view text(const Json &json, std::string_view key) { + const auto *string = protocol::as_string(&field(json, key)); + require(string != nullptr); + return *string; +} + +const Json::Array &frames(const Json &json) { + return std::get(field(json, "frames").value); +} + +std::string_view value_bits(const Json &frame) { return text(field(frame, "value"), "bitsHex"); } + +void expect_active_value(const ReplayRecording &recording, std::uint32_t seq, + std::string_view bits) { + auto cursor = checked(recording.cursor_at(seq)); + require(!frames(cursor).empty()); + expect_eq(value_bits(frames(cursor).back()), bits); +} + +void expect_point(std::expected, std::string> result, + std::uint32_t value, std::optional stop) { + const auto point = checked(std::move(result)); + require(point.has_value()); + expect_eq(point->value_sequence, value); + expect_eq(point->stop_sequence, stop); +} + +std::string read_bytes(const fs::path &path) { + std::ifstream in(path, std::ios::binary); + require(in.good()); + return {std::istreambuf_iterator{in}, std::istreambuf_iterator{}}; +} + +void write_bytes(const fs::path &path, std::string_view data, + std::ios::openmode mode = std::ios::trunc) { + std::ofstream out(path, mode | std::ios::binary); + out.write(data.data(), static_cast(data.size())); + out.close(); + require(out.good()); +} + +// Produce a checksum-valid suffix the real writer would reject. Keep hash failure distinct +// from transcript failure when testing the immutable reader's verified prefix. +void append_hashed_event(const fs::path &path, std::size_t previous_record, + std::string_view event) { + const auto bytes = read_bytes(path); + const auto previous_digest = bytes.substr(previous_record + 5, 32); + require(previous_digest.size() == 32); + const auto size = event.size(); + const std::array header{'E', static_cast(size >> 24), static_cast(size >> 16), + static_cast(size >> 8), static_cast(size)}; + auto preimage = previous_digest; + preimage.append(header.data(), header.size()).append(event); + const auto hash = Void::Crypto::sha256(preimage); + require(hash && hash->size() == 32); + std::string record{header.data(), header.size()}; + record.append(reinterpret_cast(hash->data()), hash->size()).append(event); + write_bytes(path, record, std::ios::app); +} + +} // namespace + +VOID_TEST(RecordingTests, retains_values_and_source_across_overwrite_replacement_and_unlink) { + Void::FileSystem::TempDir dir{"vls_recording_"}; + const auto path = dir / "selected"; + const auto edited = dir / "edited"; + write_pair(path, 17); + write_pair(edited, 41); + const auto old = checked(ReplayRecording::open(path)); + const auto old_page = checked(old->event_page(5, 2)); + const auto saved_source = old->source_bytes(); + require(fs::copy_file(edited, path, fs::copy_options::overwrite_existing)); + const auto newer = checked(ReplayRecording::open(path)); + expect_active_value(*old, 6, "00000011"); + expect_active_value(*newer, 6, "00000029"); + + const auto replacement = dir / "replacement"; + write_pair(replacement, 17, "step"); + fs::rename(replacement, path); + const auto replaced = checked(ReplayRecording::open(path)); + require(fs::remove(path)); + expect(!ReplayRecording::open(path)); + expect_active_value(*old, 10, "00000022"); + expect_active_value(*newer, 10, "00000052"); + expect_eq(saved_source, "int answer = 17;\n"sv); + expect_eq(newer->source_bytes(), "int answer = 41;\n"sv); + expect(old->metadata().source_sha256 != newer->metadata().source_sha256); + expect_eq(old->metadata().compiler_sha256, digest); + expect_eq(old->metadata().pid, pid); + expect_eq(old_page[1].kind, "stopped"sv); + expect_eq(checked(replaced->event_page(11, 1))[0].acknowledged_action, std::optional{"step"sv}); +} + +VOID_TEST(RecordingTests, separates_event_time_authorization_acknowledgement_and_wait) { + Void::FileSystem::TempDir dir{"vls_recording_"}; + const auto path = dir / "selected"; + Writer writer{path}; + const auto before_hello = checked(ReplayRecording::open(path)); + writer.inner_stop(17); + checked(writer.trace->authorize(6, "step")); + const auto pending = checked(ReplayRecording::open(path)); + writer.frame("resumed", 3, 1, R"(,"stop":6,"action":"step")"); + writer.frame("leave", 3, 1, R"(,"outcome":"returned")"); + writer.integer(1, {}, 34); + writer.frame("stopped", 1, {}); + writer.finish_pair("step"); + const auto step = checked(ReplayRecording::open(path)); + write_pair(dir / "continue", 17); + const auto continued = checked(ReplayRecording::open(dir / "continue")); + + expect_eq(before_hello->event_count(), std::size_t{0}); + expect(!before_hello->cursor_at(0)); + expect(!checked(before_hello->next_value())); + expect(std::holds_alternative( + field(before_hello->final_cursor(), "sequence").value)); + expect(before_hello->metadata().partial && !before_hello->metadata().corrupt); + expect(!before_hello->metadata().outcome && !before_hello->metadata().journal_error); + + expect_eq(pending->event_count(), std::size_t{7}); + const auto paused_cursor = checked(pending->cursor_at(6)); + expect_eq(protocol::as_uint32(member(paused_cursor, "stop")), std::optional{6}); + expect(std::holds_alternative(field(paused_cursor, "pendingAction").value)); + const auto authorized = pending->final_cursor(); + expect_eq(text(authorized, "pendingAction"), "step"sv); + expect(std::holds_alternative(field(authorized, "stop").value)); + expect(!pending->cursor_at(7)); + expect(!checked(pending->event_page(6, 1))[0].acknowledged_action); + expect(!pending->metadata().outcome); + + for (const auto &recording : {step, continued}) { + const auto summary = checked(recording->event_page(11, 1))[0]; + expect_eq(summary.kind, "resumed"sv); + expect_eq(summary.frame, std::optional{1}); + expect(!summary.parent); + expect_eq(summary.acknowledged_stop, std::optional{10}); + expect_eq(summary.acknowledged_action, + std::optional{recording == step ? "step"sv : "continue"sv}); + const auto historical = checked(recording->cursor_at(6)); + expect(member(historical, "outcome") == nullptr && member(historical, "source") == nullptr); + expect(member(historical, "diagnostics") == nullptr && + member(historical, "partial") == nullptr); + expect_eq(text(historical, "nonce"), nonce); + expect_eq(text(frames(historical).back(), "sourceKind"), "logicalDeclaration"sv); + expect_eq(recording->metadata().outcome, std::optional{"completed"sv}); + expect_eq(recording->metadata().exit_code, std::optional{0}); + expect(!recording->metadata().partial); + } +} + +VOID_TEST(RecordingTests, navigates_observed_integer_values_and_optional_stops_in_both_directions) { + Void::FileSystem::TempDir dir{"vls_recording_"}; + const auto path = dir / "selected"; + Writer writer{path}; + writer.inner_stop(17); + writer.outer_stop(34); + checked(writer.trace->authorize(10, "continue")); + writer.frame("resumed", 1, {}, R"(,"stop":10,"action":"continue")"); + writer.frame("leave", 1, {}, R"(,"outcome":"returned")"); + writer.enter({}, "unavailable"); + writer.frame("body", 13, {}); + writer.frame("value", 13, {}, + R"(,"value":{"kind":"unavailable","reason":"unsupportedScalar"})"); + writer.frame("leave", 13, {}, R"(,"outcome":"returned")"); + writer.enter({}, "unattended"); + writer.frame("body", 17, {}); + writer.integer(17, {}, 22); + writer.frame("leave", 17, {}, R"(,"outcome":"returned")"); + writer.event("frontendEnd"); + const auto recording = checked(ReplayRecording::open(path)); + expect_point(recording->next_value(), 5, 6); + expect_point(recording->next_value(5), 9, 10); + expect_point(recording->next_value(6), 9, 10); + expect_point(recording->next_value(10), 19, {}); + expect_point(recording->previous_value(), 19, {}); + expect_point(recording->previous_value(19), 9, 10); + expect_point(recording->previous_value(10), 5, 6); + expect_point(recording->previous_value(9), 5, 6); + expect(!checked(recording->previous_value(6))); + expect(!checked(recording->next_value(19))); + expect(!recording->previous_value(22)); + expect(!recording->next_value(std::numeric_limits::max())); + expect_eq(recording->event_count(), std::size_t{22}); + const auto page = checked(recording->event_page(3, 3)); + require(page.size() == 3); + expect_eq(page[0].sequence, 3u); + expect_eq(page[2].kind, "value"sv); + expect_eq(page[2].parent, std::optional{1}); + expect(&page[2] == checked(recording->event_page(5, 1)).data()); + expect(checked(recording->event_page(22, 256)).empty()); + expect(checked(recording->event_page(8, 0)).empty()); + expect_eq(checked(recording->event_page(21, 256)).size(), std::size_t{1}); + expect(!recording->event_page(23, 0)); + expect(!recording->event_page(0, ReplayRecording::max_page_size + 1)); + expect(!recording->event_page(std::numeric_limits::max(), 1)); + expect(recording->metadata().partial && !recording->metadata().exit_code); + expect(std::get(field(recording->final_cursor(), "frontendEnded").value)); +} + +VOID_TEST(RecordingTests, preserves_provisional_value_failed_leave_and_raw_binary_bytes) { + Void::FileSystem::TempDir dir{"vls_recording_"}; + const auto path = dir / "selected"; + constexpr auto source = "a\0\xffz"sv; + constexpr auto diagnostics = "err\0\xfe"sv; + Writer writer{path, source}; + writer.hello(); + writer.enter({}, "cleanup"); + writer.frame("body", 1, {}); + writer.integer(1, {}, 9); + writer.frame("leave", 1, {}, R"(,"outcome":"failed")"); + writer.event("frontendEnd"); + const auto before_wait = checked(ReplayRecording::open(path)); + checked(writer.trace->finish("failed", 1, diagnostics)); + const auto recording = checked(ReplayRecording::open(path)); + const auto prior = checked(recording->cursor_at(2)); + expect(member(frames(prior).back(), "value") == nullptr); + const auto produced = checked(recording->cursor_at(3)); + expect_eq(value_bits(frames(produced).back()), "00000009"sv); + expect(std::get(field(frames(produced).back(), "valueProvisional").value)); + expect(member(frames(produced).back(), "outcome") == nullptr); + const auto later = checked(recording->cursor_at(4)); + expect(frames(later).empty()); + const auto &leave = field(later, "lastLeave"); + expect_eq(value_bits(leave), "00000009"sv); + expect_eq(text(leave, "outcome"), "failed"sv); + expect(std::get(field(leave, "valueProvisional").value)); + expect(!before_wait->diagnostic_bytes()); + expect(!before_wait->metadata().outcome); + expect_eq(recording->source_bytes(), source); + expect_eq(recording->diagnostic_bytes(), std::optional{diagnostics}); + expect_eq(recording->metadata().outcome, std::optional{"failed"sv}); + expect_eq(recording->metadata().exit_code, std::optional{1}); + expect(!recording->metadata().partial); +} + +VOID_TEST(RecordingTests, separates_truncated_corrupt_and_unverified_outcome_tails) { + Void::FileSystem::TempDir dir{"vls_recording_"}; + const auto path = dir / "selected"; + write_pair(path, 17); + const auto original = read_bytes(path); + fs::resize_file(path, original.size() - 1); + const auto torn = checked(ReplayRecording::open(path)); + expect(torn->metadata().partial && !torn->metadata().corrupt); + require(torn->metadata().journal_error.has_value()); + expect_eq(*torn->metadata().journal_error, "truncated trace journal record"sv); + expect_eq(torn->event_count(), std::size_t{14}); + expect(!torn->metadata().outcome && !torn->diagnostic_bytes()); + expect_active_value(*torn, 6, "00000011"); + expect(!torn->cursor_at(14)); + + write_bytes(path, original + "x"); + const auto extra = checked(ReplayRecording::open(path)); + expect(extra->metadata().partial && extra->metadata().corrupt); + expect(!extra->metadata().outcome && !extra->diagnostic_bytes()); + expect_eq(extra->event_count(), torn->event_count()); + expect_eq(extra->metadata().journal_error, + std::optional{"trace journal has data after its process outcome"sv}); + + auto corrupt = original; + const auto offset = corrupt.find("reflected_value"); + require(offset != corrupt.npos); + corrupt[offset] = 'X'; + write_bytes(path, corrupt); + const auto prefix = checked(ReplayRecording::open(path)); + expect(prefix->metadata().corrupt); + expect_eq(prefix->event_count(), std::size_t{3}); + expect(!prefix->cursor_at(3) && !checked(prefix->next_value())); + expect_eq(frames(prefix->final_cursor()).size(), std::size_t{1}); + write_bytes(path, original.substr(0, 12)); + expect(!ReplayRecording::open(path)); + expect(!ReplayRecording::open(path.filename())); + expect(!ReplayRecording::open(dir.path())); +} + +VOID_TEST(RecordingTests, rejects_checksum_valid_duplicate_skipped_and_invalid_frame_events) { + Void::FileSystem::TempDir dir{"vls_recording_"}; + const auto path = dir / "selected"; + Writer writer{path}; + const auto hello_offset = fs::file_size(path); + writer.hello(); + const auto good = read_bytes(path); + for (const auto &event : {wire(0, "frontendEnd"), wire(2, "frontendEnd"), + wire(1, "body", R"(,"frame":1,"parent":null)")}) { + write_bytes(path, good); + append_hashed_event(path, hello_offset, event); + const auto recording = checked(ReplayRecording::open(path)); + expect_eq(recording->event_count(), std::size_t{1}); + expect(recording->metadata().corrupt && recording->metadata().partial); + expect(!recording->cursor_at(1)); + require(recording->metadata().journal_error.has_value()); + expect(recording->metadata().journal_error->starts_with("invalid compiler trace")); + const auto first = checked(recording->event_page(0, 1))[0]; + expect_eq(first.kind, "hello"sv); + expect(!first.frame && !first.parent && !first.acknowledged_stop); + } + // The reader must bound allocation by verified record lengths even for a huge sparse file. + write_bytes(path, good); + fs::resize_file(path, 1ull << 30); + const auto sparse = checked(ReplayRecording::open(path)); + expect(sparse->metadata().corrupt && sparse->event_count() == 1); +} + +VOID_TEST(RecordingTests, seeks_and_pages_at_the_event_limit_with_deep_nesting) { + Void::FileSystem::TempDir dir{"vls_recording_"}; + const auto path = dir / "selected"; + Writer writer{path}; + constexpr std::uint32_t depth = 2047; + writer.hello(); + for (std::uint32_t id = 1; id <= depth; ++id) { + writer.enter(id == 1 ? std::nullopt : std::optional{id - 1}, "nested"); + } + for (auto id = depth; id > 0; --id) { + writer.frame("leave", id, id == 1 ? std::nullopt : std::optional{id - 1}, + R"(,"outcome":"returned")"); + } + writer.event("frontendEnd"); + checked(writer.trace->finish("completed", 0, "")); + const auto recording = checked(ReplayRecording::open(path)); + expect_eq(recording->event_count(), std::size_t{4096}); + expect(!recording->cursor_at(4096)); + for (std::size_t offset = 0; offset < recording->event_count(); offset += 256) { + const auto page = checked(recording->event_page(offset, 256)); + require(page.size() == 256); + expect_eq(page.front().sequence, static_cast(offset)); + expect_eq(page.back().sequence, static_cast(offset + 255)); + } + const auto full = checked(recording->cursor_at(depth)); + const auto &stack = frames(full); + require(stack.size() == depth); + expect(std::holds_alternative(field(stack.front(), "parent").value)); + expect_eq(protocol::as_uint32(member(stack.back(), "frame")), std::optional{depth}); + expect_eq(protocol::as_uint32(member(stack.back(), "parent")), std::optional{depth - 1}); + const auto half = checked(recording->cursor_at(depth + 1024)); + expect_eq(frames(half).size(), std::size_t{depth - 1024}); + expect_eq(protocol::as_uint32(member(field(half, "lastLeave"), "frame")), + std::optional{depth - 1023}); + expect(frames(recording->final_cursor()).empty()); + expect(!checked(recording->next_value())); +} + +VOID_TEST(RecordingTests, concurrent_readers_keep_independent_cursors_after_removal) { + Void::FileSystem::TempDir dir{"vls_recording_"}; + const auto path = dir / "selected"; + write_pair(path, 17); + auto owner = checked(ReplayRecording::open(path)); + require(fs::remove(path)); + const auto at_inner = checked(protocol::serialize_json(checked(owner->cursor_at(6)))); + const auto at_outer = checked(protocol::serialize_json(checked(owner->cursor_at(10)))); + std::atomic consistent{true}; + std::barrier start{9}; + std::vector readers; + for (unsigned i = 0; i < 8; ++i) { + readers.emplace_back([owner, i, &at_inner, &at_outer, &consistent, &start] { + start.arrive_and_wait(); + for (unsigned run = 0; run < 64; ++run) { + const bool inner = (run + i) % 2 == 0; + auto state = owner->cursor_at(inner ? 6 : 10); + auto page = owner->event_page(7, 1); + if (!state || + protocol::serialize_json(*state).value_or("") != + (inner ? at_inner : at_outer) || + !page || page->front().acknowledged_action != std::optional{"step"sv} || + owner->source_bytes() != "int answer = 17;\n"sv) { + consistent = false; + return; + } + } + }); + } + owner.reset(); + start.arrive_and_wait(); + readers.clear(); // Join each owner before checking its result. + expect(consistent.load()); +} diff --git a/tests/debug/TraceTests.cpp b/tests/debug/TraceTests.cpp new file mode 100644 index 0000000..1d5d506 --- /dev/null +++ b/tests/debug/TraceTests.cpp @@ -0,0 +1,575 @@ +#include "../../experiments/frontend/gcc-worker/Trace.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace fs = std::filesystem; +namespace protocol = Void::LanguageServer::Protocol; +using protocol::Json; +using vls::gcc::replay; +using vls::gcc::Trace; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; +using namespace std::string_view_literals; + +constexpr auto nonce = "00112233445566778899aabbccddeeff"sv; +constexpr auto digest = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"sv; +constexpr auto source_17 = "int answer = 17;\n"sv; +constexpr std::int64_t pid = 4321; + +// Exact field shapes from the accepted GCC evaluator witness. These tests never start a compiler. +constexpr auto hello = + R"({"v":1,"nonce":"00112233445566778899aabbccddeeff","seq":0,"kind":"hello","backend":"gcc-16.2.0/vls-eval-1","pid":4321,"capabilities":["integralReturn","cooperativeStep"],"kinds":["hello","enter","body","value","cached","stopped","resumed","leave","terminal","frontendEnd"]})"sv; +constexpr auto no_source = R"(,"sourceKind":"unavailable")"sv; +constexpr auto value_17 = + R"(,"value":{"kind":"integer","precision":32,"signed":true,"bitsHex":"00000011"})"sv; +constexpr auto value_34 = + R"(,"value":{"kind":"integer","precision":32,"signed":true,"bitsHex":"00000022"})"sv; +constexpr auto unavailable = R"(,"value":{"kind":"unavailable","reason":"unsupportedScalar"})"sv; + +struct Fixture { + Void::FileSystem::TempDir directory{"vls_trace_"}; + fs::path journal = directory / "trace"; + + std::unique_ptr create(std::string_view source = source_17) const { + auto trace = Trace::create(journal, source, digest, nonce, pid); + require(trace.has_value()); + return std::move(*trace); + } +}; + +const Json &field(const Json &json, std::string_view key) { + const auto *object = protocol::as_object(&json); + require(object != nullptr); + const auto *value = protocol::find_member(*object, key); + require(value != nullptr); + return *value; +} + +std::string_view text(const Json &json, std::string_view key) { + const auto *value = protocol::as_string(&field(json, key)); + require(value != nullptr); + return *value; +} + +std::int64_t number(const Json &json, std::string_view key) { + const auto *value = std::get_if(&field(json, key).value); + require(value != nullptr); + return *value; +} + +bool flag(const Json &json, std::string_view key) { return std::get(field(json, key).value); } + +bool null(const Json &json, std::string_view key) { + return std::holds_alternative(field(json, key).value); +} + +const Json::Array &frames(const Json &json) { + return std::get(field(json, "frames").value); +} + +std::string_view bits(const Json &frame) { return text(field(frame, "value"), "bitsHex"); } + +std::string wire(std::uint32_t seq, std::string_view kind, std::string_view members = {}) { + return std::format(R"({{"v":1,"nonce":"{}","seq":{},"kind":"{}"{}}})", nonce, seq, kind, + members); +} + +std::string frame(std::uint32_t seq, std::string_view kind, std::uint32_t id, + std::string_view parent, std::string_view members = {}) { + return wire(seq, kind, std::format(R"(,"frame":{},"parent":{}{})", id, parent, members)); +} + +std::string enter(std::uint32_t seq, std::string_view parent, std::string_view name) { + return frame(seq, "enter", seq, parent, std::format(R"(,"name":{}{})", name, no_source)); +} + +std::string replaced(std::string_view original, std::string_view before, std::string_view after) { + std::string changed{original}; + const auto offset = changed.find(before); + require(offset != changed.npos); + changed.replace(offset, before.size(), after); + return changed; +} + +void add(Trace &trace, std::string_view line, + std::source_location at = std::source_location::current()) { + const auto result = trace.event(line); + expect_eq(result ? ""sv : std::string_view{result.error()}, ""sv, at); + require(result.has_value(), at); +} + +Json read(const fs::path &path, std::optional seq = std::nullopt, + std::source_location at = std::source_location::current()) { + auto result = replay(path, seq); + expect_eq(result ? ""sv : std::string_view{result.error()}, ""sv, at); + require(result.has_value(), at); + return std::move(*result); +} + +void put_file(const fs::path &path, std::string_view data, + std::ios::openmode mode = std::ios::trunc) { + std::ofstream file(path, std::ios::binary | mode); + file.write(data.data(), static_cast(data.size())); + file.close(); + require(file.good()); +} + +std::string file_bytes(const fs::path &path) { + std::ifstream file(path, std::ios::binary); + require(file.good()); + return {std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; +} + +void first_stop(Trace &trace) { + add(trace, hello); + add(trace, enter(1, "null", R"("twice")")); + add(trace, frame(2, "body", 1, "null")); + add(trace, + frame( + 3, "enter", 3, "1", + R"(,"name":"reflected_value","sourceKind":"logicalDeclaration","source":"input.cpp","line":5,"byteColumn":15)")); + add(trace, frame(4, "body", 3, "1")); + add(trace, frame(5, "value", 3, "1", value_17)); + add(trace, frame(6, "stopped", 3, "1")); +} + +} // namespace + +VOID_TEST(TraceTests, strict_handshake_and_envelope_reject_without_advancing) { + const Fixture fixture; + const auto trace = fixture.create(); + const auto initial_bytes = fs::file_size(fixture.journal); + expect(null(trace->inspection(), "sequence")); + expect(!trace->event(wire(0, "frontendEnd"))); + expect(!trace->event(replaced(hello, nonce, "10112233445566778899aabbccddeeff"))); + expect(!trace->event(replaced(hello, "4321", "4322"))); + expect(!trace->event(replaced(hello, "4321", "4321.0"))); + expect(!trace->event(replaced(hello, "vls-eval-1", "vls-ide-1"))); + expect(!trace->event(replaced(hello, "cooperativeStep", "integralReturn"))); + expect(!trace->event(replaced(hello, R"("frontendEnd"])", R"("terminal"])"))); + expect(!trace->event(replaced(hello, R"("v":1)", R"("v":1.00000000000000001)"))); + expect(!trace->event(replaced(hello, R"("seq":0)", R"("seq":0,"seq":0)"))); + expect(!trace->event(std::string{hello} + '\n')); + expect_eq(fs::file_size(fixture.journal), initial_bytes); + add(*trace, hello); + expect(!trace->event(wire(2, "frontendEnd"))); + expect(!trace->event(replaced(wire(1, "frontendEnd"), R"("seq":1)", R"("seq":1e0)"))); + expect(!trace->event(hello)); + expect_eq(number(read(fixture.journal), "sequence"), std::int64_t{0}); + add(*trace, wire(1, "frontendEnd")); + expect(!trace->event(wire(2, "frontendEnd"))); +} + +VOID_TEST(TraceTests, frame_identity_parent_and_actual_body_are_required) { + const Fixture fixture; + const auto trace = fixture.create(); + add(*trace, hello); + expect( + !trace->event(frame(1, "enter", 2, "null", R"(,"name":null,"sourceKind":"unavailable")"))); + expect(!trace->event(enter(1, "0", "null"))); + expect(!trace->event(enter(1, "null", R"("\u0001")"))); + add(*trace, enter(1, "null", "null")); + expect(!trace->event(wire(2, "body", R"(,"frame":1)"))); + expect(!trace->event(wire(2, "frontendEnd"))); + expect(!trace->event(frame(2, "value", 1, "null", value_17))); + // GCC can enter a child during parameter work or lazy instantiation before the parent's body. + add(*trace, enter(2, "1", R"("nested")")); + expect(!trace->event(frame(3, "cached", 2, "null"))); + expect(!trace->event(frame(3, "body", 1, "null"))); + add(*trace, frame(3, "cached", 2, "1")); + expect(!trace->event(frame(4, "value", 2, "1", value_17))); + expect(!trace->event(frame(4, "body", 2, "1"))); + add(*trace, frame(4, "leave", 2, "1", R"(,"outcome":"returned")")); + const auto cached = read(fixture.journal, 4); + expect(flag(field(cached, "lastLeave"), "cached")); + expect(protocol::find_member(*protocol::as_object(&field(cached, "lastLeave")), "value") == + nullptr); + expect(!trace->event(frame(5, "enter", 2, "1", R"(,"name":null,"sourceKind":"unavailable")"))); + add(*trace, frame(5, "leave", 1, "null", R"(,"outcome":"failed")")); + add(*trace, wire(6, "frontendEnd")); + expect(trace->ended()); +} + +VOID_TEST(TraceTests, integer_width_and_unavailable_scalar_are_exact) { + const Fixture fixture; + const auto trace = fixture.create(); + add(*trace, hello); + add(*trace, enter(1, "null", R"("scalar")")); + add(*trace, frame(2, "body", 1, "null")); + for ( + const auto malformed : { + R"(,"value":{"kind":"integer","precision":0,"signed":true,"bitsHex":""})"sv, + R"(,"value":{"kind":"integer","precision":65,"signed":true,"bitsHex":"00000000000000000"})"sv, + R"(,"value":{"kind":"integer","precision":8.0,"signed":true,"bitsHex":"fd"})"sv, + R"(,"value":{"kind":"integer","precision":8,"signed":true,"bitsHex":"f"})"sv, + R"(,"value":{"kind":"integer","precision":8,"signed":true,"bitsHex":"FF"})"sv, + R"(,"value":{"kind":"integer","precision":8,"signed":1,"bitsHex":"fd"})"sv, + R"(,"value":{"kind":"integer","precision":1,"signed":false,"bitsHex":"2"})"sv, + R"(,"value":{"kind":"unavailable","reason":"other"})"sv, + }) { + expect(!trace->event(frame(3, "value", 1, "null", malformed))); + } + add(*trace, + frame( + 3, "value", 1, "null", + R"(,"value":{"kind":"integer","precision":64,"signed":false,"bitsHex":"8000000000000005"})")); + const auto copied = read(fixture.journal, 3); + expect_eq(bits(frames(copied).back()), "8000000000000005"sv); + expect(!flag(field(frames(copied).back(), "value"), "signed")); + add(*trace, frame(4, "leave", 1, "null", R"(,"outcome":"returned")")); + add(*trace, enter(5, "null", R"("wide")")); + add(*trace, frame(6, "body", 5, "null")); + add(*trace, frame(7, "value", 5, "null", unavailable)); + expect(!trace->event(frame(8, "stopped", 5, "null"))); + const auto absent = read(fixture.journal, 7); + expect_eq(text(field(frames(absent).back(), "value"), "reason"), "unsupportedScalar"sv); +} + +VOID_TEST(TraceTests, steps_through_nested_values_and_seeks_before_the_command) { + const Fixture fixture; + const auto trace = fixture.create(); + first_stop(*trace); + expect_eq(trace->stopped(), std::optional{6}); + expect(!trace->authorize(5, "step")); + expect(!trace->authorize(7, "continue")); + expect(!trace->authorize(6, "inspect")); + expect(!trace->event(frame(7, "resumed", 3, "1", R"(,"stop":6,"action":"step")"))); + require(trace->authorize(6, "step").has_value()); + expect(!trace->stopped()); + expect(!trace->authorize(6, "cancel")); + const auto pending = read(fixture.journal); + expect(null(pending, "stop")); + expect_eq(text(pending, "pendingAction"), "step"sv); + expect(!trace->event(frame(7, "leave", 3, "1", R"(,"outcome":"returned")"))); + expect(!trace->event(frame(7, "resumed", 3, "1", R"(,"stop":6,"action":"continue")"))); + expect(!trace->event(frame(7, "resumed", 3, "1", R"(,"stop":5,"action":"step")"))); + add(*trace, frame(7, "resumed", 3, "1", R"(,"stop":6,"action":"step")")); + add(*trace, frame(8, "leave", 3, "1", R"(,"outcome":"returned")")); + add(*trace, frame(9, "value", 1, "null", value_34)); + add(*trace, frame(10, "stopped", 1, "null")); + expect(!trace->authorize(6, "continue")); + require(trace->authorize(10, "continue").has_value()); + add(*trace, frame(11, "resumed", 1, "null", R"(,"stop":10,"action":"continue")")); + add(*trace, frame(12, "leave", 1, "null", R"(,"outcome":"returned")")); + add(*trace, enter(13, "null", R"("another")")); + add(*trace, frame(14, "body", 13, "null")); + add(*trace, frame(15, "value", 13, "null", value_17)); + expect(!trace->event(frame(16, "stopped", 13, "null"))); + add(*trace, frame(16, "leave", 13, "null", R"(,"outcome":"returned")")); + add(*trace, wire(17, "frontendEnd")); + require(trace->finish("completed", 0, "").has_value()); + + const auto inner = read(fixture.journal, 6); + require(frames(inner).size() == 2); + expect_eq(text(frames(inner).front(), "name"), "twice"sv); + expect_eq(text(frames(inner).back(), "name"), "reflected_value"sv); + expect_eq(bits(frames(inner).back()), "00000011"sv); + expect(flag(frames(inner).back(), "valueProvisional")); + expect_eq(number(inner, "stop"), std::int64_t{6}); + expect(null(inner, "pendingAction")); + expect_eq(text(inner, "outcome"), "completed"sv); + expect(!flag(inner, "frontendEnded")); + expect(!flag(inner, "partial")); + + const auto after_leave = read(fixture.journal, 8); + require(frames(after_leave).size() == 1); + expect(!flag(field(after_leave, "lastLeave"), "valueProvisional")); + expect_eq(bits(field(after_leave, "lastLeave")), "00000011"sv); + const auto outer = read(fixture.journal, 10); + require(frames(outer).size() == 1); + expect_eq(number(outer, "stop"), std::int64_t{10}); + expect_eq(bits(frames(outer).back()), "00000022"sv); + const auto final = read(fixture.journal); + expect(flag(final, "frontendEnded")); + expect(frames(final).empty()); + expect(!replay(fixture.journal, 18)); +} + +VOID_TEST(TraceTests, cancellation_keeps_the_open_provisional_frame) { + const Fixture fixture; + auto trace = fixture.create(); + first_stop(*trace); + const auto cancelled = wire(7, "terminal", R"(,"reason":"cancelled","stop":6)"); + expect(!trace->event(cancelled)); + require(trace->authorize(6, "cancel").has_value()); + expect(!trace->event(frame(7, "resumed", 3, "1", R"(,"stop":6,"action":"cancel")"))); + expect(!trace->event(wire(7, "terminal", R"(,"reason":"cancelled","stop":5)"))); + add(*trace, cancelled); + expect_eq(trace->terminal(), "cancelled"sv); + expect(!trace->stopped()); + expect(!trace->ended()); + expect(!trace->finish("completed", 0, "")); + require(trace->finish("cancelled", 125, "").has_value()); + trace.reset(); + + const auto recorded = read(fixture.journal); + require(frames(recorded).size() == 2); + expect_eq(bits(frames(recorded).back()), "00000011"sv); + expect(flag(frames(recorded).back(), "valueProvisional")); + expect(protocol::find_member(*protocol::as_object(&frames(recorded).front()), "value") == + nullptr); + expect(flag(recorded, "partial")); + expect(!flag(recorded, "corrupt")); + expect_eq(text(recorded, "outcome"), "cancelled"sv); + expect_eq(number(recorded, "exitCode"), std::int64_t{125}); + expect_eq(number(read(fixture.journal, 6), "stop"), std::int64_t{6}); +} + +VOID_TEST(TraceTests, frontend_end_and_provisional_value_do_not_prove_success) { + const Fixture fixture; + const auto trace = fixture.create(); + add(*trace, hello); + add(*trace, enter(1, "null", R"("candidate")")); + add(*trace, frame(2, "body", 1, "null")); + add(*trace, frame(3, "value", 1, "null", replaced(value_17, "00000011", "00000009"))); + add(*trace, frame(4, "leave", 1, "null", R"(,"outcome":"failed")")); + expect(!trace->finish("completed", 0, "")); + add(*trace, wire(5, "frontendEnd")); + expect(!trace->finish("completed", 1, "unmatched")); + expect(!trace->finish("another", 1, "unknown")); + const auto before_wait = read(fixture.journal); + expect(flag(before_wait, "frontendEnded")); + expect(flag(before_wait, "partial")); + expect(null(before_wait, "outcome")); + require(trace->finish("failed", 1, "cleanup failed\n").has_value()); + expect(!trace->finish("completed", 0, "")); + const auto recorded = read(fixture.journal); + expect(frames(recorded).empty()); + const auto &leave = field(recorded, "lastLeave"); + expect_eq(text(leave, "outcome"), "failed"sv); + expect_eq(bits(leave), "00000009"sv); + expect(flag(leave, "valueProvisional")); + expect_eq(text(recorded, "outcome"), "failed"sv); + expect_eq(text(recorded, "diagnostics"), "cleanup failed\n"sv); + expect(!flag(recorded, "partial")); +} + +VOID_TEST(TraceTests, replay_keeps_source_bytes_after_edit_and_removal) { + const Fixture fixture; + const auto original = fixture.directory / "input.cpp"; + put_file(original, source_17); + auto trace = fixture.create(file_bytes(original)); + first_stop(*trace); + trace.reset(); + put_file(original, "int answer = 41;\n"); + const auto edited = read(fixture.journal); + expect_eq(text(edited, "source"), source_17); + expect_eq(text(edited, "sourceSha256"), + "e2727305e817a0da9431b286b4317caec93433b6bc372f242b2786944c60c28f"sv); + expect_eq(text(edited, "compilerSha256"), digest); + expect_eq(bits(frames(edited).back()), "00000011"sv); + require(fs::remove(original)); + const auto journal_before = file_bytes(fixture.journal); + require(::chmod(fixture.journal.c_str(), 0400) == 0); + const auto removed = read(fixture.journal, 6); + expect_eq(text(removed, "source"), source_17); + expect_eq(text(frames(removed).back(), "source"), "input.cpp"sv); + expect(null(removed, "outcome")); + expect(flag(removed, "partial")); + expect_eq(file_bytes(fixture.journal), journal_before); +} + +VOID_TEST(TraceTests, captured_binary_bytes_round_trip_in_json_projection) { + const Fixture fixture; + const auto trace = fixture.create("\xff\0x"sv); + require(trace->finish("failed", 126, "\x80\n"sv).has_value()); + const auto recorded = read(fixture.journal); + expect(null(recorded, "source")); + expect_eq(text(recorded, "sourceHex"), "ff0078"sv); + expect_eq(text(recorded, "sourceSha256"), + "b56ed79fd4921608ee3cc257a4bb1a7b726bf67c84a26f3e3ca41aa42c6e9737"sv); + expect(null(recorded, "diagnostics")); + expect_eq(text(recorded, "diagnosticsHex"), "800a"sv); + expect(protocol::serialize_json(recorded).has_value()); +} + +VOID_TEST(TraceTests, replay_recovers_verified_prefix_on_truncation_or_tampering) { + const Fixture fixture; + auto trace = fixture.create(); + first_stop(*trace); + require(trace->authorize(6, "cancel").has_value()); + add(*trace, wire(7, "terminal", R"(,"reason":"cancelled","stop":6)")); + require(trace->finish("cancelled", 125, "finished").has_value()); + trace.reset(); + const auto full = file_bytes(fixture.journal); + + fs::resize_file(fixture.journal, full.size() - 3); + const auto torn = read(fixture.journal); + expect_eq(number(torn, "sequence"), std::int64_t{7}); + expect_eq(text(torn, "terminal"), "cancelled"sv); + expect(null(torn, "outcome")); + expect(flag(torn, "partial")); + expect(!flag(torn, "corrupt")); + + put_file(fixture.journal, replaced(full, "reflected_value", "reflected_FAKE!")); + const auto tampered = read(fixture.journal); + expect_eq(number(tampered, "sequence"), std::int64_t{2}); + require(frames(tampered).size() == 1); + expect_eq(text(frames(tampered).front(), "name"), "twice"sv); + expect(null(tampered, "outcome")); + expect(flag(tampered, "partial")); + expect(flag(tampered, "corrupt")); + expect(!replay(fixture.journal, 3)); + expect(flag(read(fixture.journal, 0), "corrupt")); + + put_file(fixture.journal, replaced(full, source_17, "int answer = 41;\n")); + expect(!replay(fixture.journal, std::nullopt)); + + put_file(fixture.journal, full + "tail"); + const auto after_finish = read(fixture.journal); + expect(flag(after_finish, "corrupt")); + expect(null(after_finish, "outcome")); + expect_eq(number(after_finish, "sequence"), std::int64_t{7}); +} + +VOID_TEST(TraceTests, replay_bounds_corrupt_lengths_and_regular_file_inputs) { + const Fixture fixture; + auto trace = fixture.create(); + add(*trace, hello); + trace.reset(); + put_file(fixture.journal, "E\x7f\xff\xff\xff"sv, std::ios::app); + const auto huge_record = read(fixture.journal); + expect(flag(huge_record, "corrupt")); + expect_eq(number(huge_record, "sequence"), std::int64_t{0}); + expect_eq(text(huge_record, "journalError"), "invalid trace journal record type or length"sv); + expect(!replay(fixture.journal, 4096)); + expect(!replay(fixture.directory.path(), std::nullopt)); + const auto fifo = fixture.directory / "fifo"; + require(::mkfifo(fifo.c_str(), 0600) == 0); + expect(!replay(fifo, std::nullopt)); + const auto alias = fixture.directory / "alias"; + fs::create_symlink(fixture.journal, alias); + expect(!replay(alias, std::nullopt)); +} + +VOID_TEST(TraceTests, trace_and_record_byte_budgets_hold_at_the_boundary) { + const Fixture fixture; + const auto trace = fixture.create(); + std::string oversized{hello}; + oversized.resize(4096, ' '); + expect(!trace->event(oversized)); + expect(null(trace->inspection(), "sequence")); + + // 255 full records leave exactly 4096 bytes. Fit the final enter and terminal in that page. + std::string padded{hello}; + padded.resize(4095, ' '); + add(*trace, padded); + for (std::uint32_t seq = 1; seq < 255; seq += 2) { + padded = enter(seq, "null", "null"); + padded.resize(4095, ' '); + add(*trace, padded); + padded = frame(seq + 1, "leave", seq, "null", R"(,"outcome":"failed")"); + padded.resize(4095, ' '); + add(*trace, padded); + } + const auto terminal = wire(256, "terminal", R"(,"reason":"truncated")"); + padded = enter(255, "null", "null"); + padded.resize(4094 - terminal.size(), ' '); + add(*trace, padded); + expect(!trace->event(terminal + ' ')); // Its LF would be one byte over the budget. + expect_eq(number(trace->inspection(), "sequence"), std::int64_t{255}); + add(*trace, terminal); + expect(!trace->ended()); + require(trace->finish("truncated", 126, "").has_value()); + const auto limited = read(fixture.journal); + expect_eq(text(limited, "outcome"), "truncated"sv); + expect(flag(limited, "partial")); +} + +VOID_TEST(TraceTests, compiler_truncation_without_stop_token_is_valid) { + const Fixture fixture; + const auto trace = fixture.create(); + first_stop(*trace); + require(trace->authorize(6, "step").has_value()); + expect(!trace->event(wire(7, "terminal", R"(,"reason":"truncated","stop":6)"))); + add(*trace, wire(7, "terminal", R"(,"reason":"truncated")")); + expect_eq(trace->terminal(), "truncated"sv); + expect(!trace->stopped()); + expect(!trace->ended()); + const auto recorded = read(fixture.journal); + expect(flag(recorded, "partial")); + expect(!flag(recorded, "corrupt")); + expect_eq(bits(frames(recorded).back()), "00000011"sv); +} + +VOID_TEST(TraceTests, journal_creation_and_stop_authorization_are_exclusive) { + const Fixture fixture; + expect(!Trace::create(fixture.journal, source_17, digest, "incorrect", pid)); + expect(!Trace::create(fixture.journal, source_17, digest, nonce, 0)); + expect(!Trace::create(fixture.journal, std::string(1024 * 1024 + 1, 'x'), digest, nonce, pid)); + expect(fs::is_empty(fixture.directory.path())); + std::array, 2> recorders; + std::barrier start(2); + const auto attempt = [&](std::size_t index) { + start.arrive_and_wait(); + auto created = Trace::create(fixture.journal, source_17, digest, nonce, pid); + if (created) { + recorders[index] = std::move(*created); + } + }; + std::jthread first(attempt, 0); + attempt(1); + first.join(); + require(static_cast(recorders[0]) != static_cast(recorders[1])); + auto &trace = recorders[recorders[0] ? 0 : 1]; + struct stat status{}; + require(::stat(fixture.journal.c_str(), &status) == 0); + expect((status.st_mode & 0777) == 0600); + first_stop(*trace); + std::array accepted{}; + const auto race = [&](std::size_t index) { + start.arrive_and_wait(); + accepted[index] = trace->authorize(6, "step").has_value(); + }; + std::jthread second(race, 0); + race(1); + second.join(); + expect(accepted[0] != accepted[1]); + expect(!trace->stopped()); + const auto saved = file_bytes(fixture.journal); + expect(!Trace::create(fixture.journal, "new source", digest, nonce, pid)); + expect_eq(file_bytes(fixture.journal), saved); + expect(static_cast(std::distance(fs::directory_iterator{fixture.directory.path()}, + fs::directory_iterator{})) == 1); +} + +VOID_TEST(TraceTests, splice_origin_is_declared_validated_and_exposed) { + constexpr auto origin = + R"(,"source":"input.cpp","line":4,"byteColumn":31,"targetKind":"declaration","targetName":"Ready","targetSource":"input.cpp","targetLine":1,"targetByteColumn":20)"sv; + const Fixture legacy; + const auto old_trace = legacy.create(); + add(*old_trace, hello); + expect(!old_trace->event(wire(1, "splice", origin))); + const Fixture current; + const auto trace = current.create(); + add(*trace, replaced(hello, R"("frontendEnd"])", R"("frontendEnd","splice"])")); + expect(!trace->event(wire(1, "splice", replaced(origin, R"("line":4)", R"("line":0)")))); + expect(!trace->event( + wire(1, "splice", + replaced(origin, R"("targetKind":"declaration")", R"("targetKind":"alias")")))); + expect(!trace->event( + wire(1, "splice", replaced(origin, R"("targetLine":1)", R"("targetLine":null)")))); + add(*trace, wire(1, "splice", origin)); + const auto inspection = trace->inspection(); + const auto *origins = + protocol::as_array(protocol::find_member(*protocol::as_object(&inspection), "origins")); + require(origins != nullptr && origins->size() == 1); + expect(number(origins->front(), "line") == 4); + expect(text(origins->front(), "targetName") == "Ready"); + expect(number(origins->front(), "targetByteColumn") == 20); +} diff --git a/tests/debug/fixtures/cancelled-41.vls b/tests/debug/fixtures/cancelled-41.vls new file mode 100644 index 0000000000000000000000000000000000000000..f70edd58fa87503af4cdd70804d4606e33dcf02c GIT binary patch literal 2620 zcmbVOYitx%6fO}ktR+wpA<`c=Q-Uqh?ab`#PG|ZOmLl?$b_JA_a`(=i?!a_rIx|~n zmW>2K&=8PltfWXHBEet)F+vbcc*)C0_#u%%0w_X(M56{FiY1cx5$^zTF`ZBZtVQ{b656PJTGloJYn@<@=l=e`xT`r zCXUG>YAB4%v=CCxMS^^gt!USsa@vmda*i3t5VO_NbZR#yFdvRUU|6hV2_InvH7-b0 zWW$n(MUEw5Nr>?9j#mW|7DP29ghJuCD6k?YND-EkD6jIIs6tM|Gzf)Mm~vrKDJeV= z#BfAX6cr+chyu60i(Yw418_Vmih{t7V;nPS6Pkm*1R}KUd0+v#Fc34deg~jWiSN zxYdxVwsfAHxgs}}p(p&zRe|(B@VX0@yI3QC2h&@GM`Qcqu8!4~`mp`%6%{C!pvbbR zq7hKf@o;q@*G^KTnl_4?ZUS*4!iIue2!t?D0Qm}l@FIV?t3owKY|vb}-PZ40ug#x76oX?VDa(%9f#8 z#Fkb4TTD0`Q=+K~RnhEejm^=?_0g%#4fRv%qp|vl&C!`NVEo2EJtG$AEieT7L<%d!lgKo3 z5wHa{!%DhAVp(vgYlfE`{EBzDG-~R}R)dj4A)n=fOQV)E{Wk3@yg6adf;B4+*E}`0 zeC^ETN86qm_{zm$LwEj^FH1hhve%jWlk`CxyLEd*$Mv;;)b02T?|yjmi2>WjZ92PU z``ND5sm?uTzi7LbFNjbML?5Z)MOJFB^)ov6S(-UL^HeTkvQA^^g@jh&ssUeE7_kR4Gul@0dC-k)LE>_l_CR+dB1 zKaSR7z`V-df(I>O6;Gy1pt)K9!%Iv$)56792E976=hmgV0fWfS!cptjo>+Gv6E0hI+*0b;R tt6p_z*O;o)yZ4`dcgw&OLzif7)Kt9P!h`i@(uMzZ-e0f`KQCuG@F&NiWuyQA literal 0 HcmV?d00001 diff --git a/tests/debug/fixtures/integral-17.vls b/tests/debug/fixtures/integral-17.vls new file mode 100644 index 0000000000000000000000000000000000000000..662bfa7f4e40a443b5cf005517fba3501f554dda GIT binary patch literal 6166 zcmcgwYgiLk8urqP8`g?K)oR7*pn?jR`wfiPhy?|2T&yVIFmoaUA&HX-5+I^hYuCG5 ztxJJ=$6H~&*Q$sLt0*egRZ&1)wYZ9x>Q-AS)$W-|NMMlNXJ`AEKgn~>H|MWW{w-wlqMx-P+QkDFKiM$aV^f<|48_08yi#P%vRGYd_^ z@Kj(RP&GOe#{)$2KyjdOc)H#k0MapifC%+Rabuc^)B`Fi857IoFi@sY3URSqDAgrN zRX`z>sT7z(B*bMZsay=_#5yT1lPYu)sYD`6Qb>ggkyIrYic~bNA`=5lsFaE13QPhwV751r5S&;jQ7KhQf7EQWP&jZxfxC%t98>Br ziA*TcVJZoZ5mF^i$Z#b=sAM=0tE5VWM5+@>Byy<)6Y3O%j8G9uCBP*TDQXh{gCz~Y z^_ba=M9~-xkSt^}zz8cc0udxR?QuFpOejAuB+o!6%q}LD4OG8Zp2%N!pCiRue#= zO3a!xh2a262NbCz0Tn24C<1S#{_NvOtWw4sbkL`dQcZV!;fa6>8M)tKOG=5n1!l^{%9)6 z9`j_N*Bjxv`tJw7^~u9A6P85kNty&^R6Px4axjy^^pjcBv30^|0u;1fI*6iy35~aJ z$p$xX3VjGDW^*H9g@Oy(FvD<653qCqznPSi222ls>L?>z z$UuZbM)5W%T!-U>vq!&o2OHdJmUm#u?S_Je^>@~6`_cT%yZvwU?L6tRxR|eSP-};9 z&DeDmmIiAVoG@V&97NRyi(U^?!VaTsav3UYr5a}!U2mKT4}pF(fF*>H$Y^jzz$!=@ zOcpv2H<{p|o-{Cv!+a%KX`nUgEolZ+Es?M+XTNDU{NrDm*e*O^l^oqF39ZxLZ#YA5IYc6fE= zOkK4u>a8tdxj%06t>%jW5_TB7`4l>G-V#Fd5mje32eZeXJ;SiFRy=92tcY(@(WuZ+y?&VE&ZreJXu|FOrHao&%6R#kVT|8W_MJeb}$Yjxd8 z%_h%7mHOhWetCRxshqetPHt18?eqV)nZ;s-jgAKN({) zX`XDXJt?13xGQD@UrJ2-mCPpYa>-`v}! z2gX>ssn*x>CIb;W$h5IFhl~qS3u`+8voL2z_#_|saAgkIaO^v4XjDohRWX0<>6)73 zfBx!pk=vq|%X!0eH9?NQ+kkA(;$>*vmwU%$_M6syUg2)yLPO-+;HxRIKjbEhM$0A% z<}KdA8(X`*QPiSbzp;A=Ve@md7J97tXx{ehoKxdVBFX$iO`TNxg9{ac+Pp@skT*|P zUv%CH9Yuyqlr=*}UTV#@jD*7jAB4}%ocJoeFlA4GN9XAeUM9vJEYI;i`3`R&uJ*_^ zLmR={bwgujy;s4}YYCfotpfCjA1d6xXv*CZ_X*jhSB?0>y0ahf2IuN^oSTve&NN?@ z-k2MbJn!ARvF*8U#fq5VbAvD3DVlzQ@QX(hy2Z}wUtbyUsuORXu7241mc*sWdf`k- zpusp{VpPaex5V*oO$mls;PB&+xRT6$_a2PBv39+bHw;(fV7j;KencM%JWno9lHZ`BkB3?f4kpbY1=qA1(#I6R&ZR)L1{C*cyxud72yAK?!t64v_ z(QD)GwQ&<)_S*MsRLH|+nk{kS94$W5yOK90R~zJ(6b_~K3d*hm{NkC%hljj4a`niS zf*{Mhb-x<3^KUlw%v7&@);QENo;NgC>*K23rl9;@cPQMUcg6`#LLM3#hdx~0cxY$u z9x46So!E0(w4^*MQ@8bM9es>9DObfMG^dy1Fct6b&TN0EAK?xFaCHK=+=z~p|t zz|-FK(sa$z5 zCViKe&r)K!jCT@TeU#hKxkT*^y*#4Et^V&f`;>e6cKJT$`G!x<4JhxqsB}PB*ozSA z)Y(GbKw!>a|L=v1!yj$W4HI)pqid^@=j2C(kH51xHsd{yWMyaVg3|rRFKNrCR)&Z1 z2Ip#YEnjWf#=!rogRIE)VGGw${$~~~Ieffcv*^RQ3v>;ejy{;9Axi^#%_+-5K?X@{ XjRgG51*@hDJoDmS58z8x_?G+M|HJjC literal 0 HcmV?d00001 diff --git a/tests/debug/fixtures/integral-41.vls b/tests/debug/fixtures/integral-41.vls new file mode 100644 index 0000000000000000000000000000000000000000..4aedbd5d8b57e9bd672b1fdbc777980d484d1b2c GIT binary patch literal 6166 zcmcgwc~BEs9!AFzjn}T=sJKYmAcq3x4he{2K=1+t1Vs)z-7nA@lGy1Wh*1Zx6+B7> zk5NmV@?b<6g;7V81(o$c9oJFD8)v}P)pDJ}WxU7T*PW0+BeS)=Q|6zf-uw0Mec$)H zUOI7dd_tUBB$(pl^vNp2(1vY6`00wTmi0T)>uz?j=JC8?$%4UYh$gM*j9=!PJXC|> zbAX;eRcHo|2Z-c>;y~f3Y@I0pWMjGj5$ccPhAbng15|t_CYH&ep-d4Z#Km%HMzm*cpEkl{*^RxHGnVrXh4Avm#6A(u+T{;0`drf^_~B2tJ62|)zO zL`tO`mqGW0TrO2AwQ>zE1rlwLh|uCnB~FL|AyZ;938BD*Qusrp!NpQJhFSzbZ_Yw+ z9cD5i@iayQBoB!L7?F#NMx-Ld5-bqVAj_zOJ0Vu9gir)$;2UWq3Ny9ZQedu`q<{%N zo}f~(tHJG`wi{a=m}o{}gw)dr1++SV(||~aD`w!!tZ7Kh9ArXCfj6g6Ro_ zhKA4#DuA#GK;;9Or*jd=+F$|#=u8htXhyNNkQJb^;1f)|py*~Djp(6Ik~Sf9t`Q(m zCB`RBVK_jt0Yz#_Km`hH%D`9yiuPssg|I;n^%eRdp@`5g__u6itu~&dmH=8LadLdR zIx0dvDLpP?VuU&&B0OCk6AjBRY(jK`fD<(e%w}T@<7PdW4GnXmC#*kGD~ND%>f&15 zjLxp9Xbd0dQ$McQQ+cW8z_s*1^Ml0Wxmn%gnwIMG&}>vC`kxBO1m>bDp+7o@WXn7g z=yV2HSO2~6+gBcr88Hp1BWV(tP}NM7i9rU1>EhU=WBY``2q>6(*&v<NXn|Tz&GXVjAm}rC1$o^uY3L^~HbO6f+@S6!asmFBirULCf7!uHgKqa??ttX6Iv!B;q_wN1EI>{<%T zg1rlF7%>ViqAI;vr-LD3mr*vj3>CIhO|puvGi1Ob(1iooLKuk*dbwk4OOs0jwLxdj(xWPggk?Ev;rG>U6?JR19^=3BI%C;-x^b~$=q2O4AxX8R z-cjVy-F#WX&T3<6i_C{fvLMb`B5wCT8FwVIWJhgdz~LWeeR=++>x3`IxnDJGsvj1; zu7EEHi5&z-YPiuVHIw>QojFa@t|w2$WgNlfEZ5X=nVXwORA$Q?-?*F_qK=kl`w~HA zpD!Af1ft>-tGvhX{m!53YS9bIcn z{vbAknTA(J=5}YjD!`;*ag~kU6T6|jZ$bLzrTy!R!@u>SwqI%5;pE({k7${@$x7uX4>p`PtwLURTh7$}zu;mLK?WK=q;e9)@a<@ai@R z4eup1sW&qtmGR9C8#X@qMcWIL(@xE-^n5fgrtJESMeq6tpL^$=d&cKU#aCoasS9s1 z5V4I+hqUI9aX@O5+IGM!%y~_|+XWYTR4sfv;8=a>$kkOAx9;JVTfb7*-d}wf8Xxcl zZxAUjL(GieRVeAVNdU3+hCF)Z&kc0hpc&0cC=&!$^(hXSf5KXc}dt<%{k zYSXSi+C79AL57dMNGSXJ%E%)w@@~&}kGVm5=kMwM{e4gJuUD?l=greG7wvaKTa)1u zWs@OC8d*6hrFn7gwimnNJ}HbME+>~ezpL8zXyuZ-KdZvJT;mPIF&??e&_VD{vmvwZ z`u_I@-f}I7a<8r|`tD%y(RCF)F5H^bvigq3q%z;)4bCy^I5#B`+-bckeY9-QR4(1? z?o6&9xxyuK@|_9Jzxr11Eq~M9|M-Hs$7`1dUGB%5r(+(rza?>Lvbj)qYGGO7{FEOX z=6*IZL$2R9xaaL1C0itYR!nPN@OGH==3U+}9D|Q5H{5BJo5A!kucouyf;@-Z4!fAA zUW1lB@QClZJhJLgxA*S`F56A5?j3PZ#+$BVo^n)g$ClN+tVwhJc8E)2!|axCg!taV zRjx^08W!C-R+~KbrMz!l-eA5U#Et>T9qR2+{C*cyV4LaL%ba7&!#6hlA^q5aR|5)r zZH`HO5lKjohx%RiDw#WRY$DI7|jHIzefrw3IO?Oi&*yi}br^RCn@bE{!e z$%&y}8|kCddjv%B9xr0Y=;Ny0p`rXHX-)Q3$nf5EplmU3 zATZ{(ODHEBxH$aL&axpkJ;nb?W4yb;*UNLr8*8=b9SMyMiL(*yk W0snHruIT{Jytvl^_)- + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace Void::LanguageServer::Documents; +using Void::Testing::expect; +using Void::Testing::require; +using Kind = DocumentError::Kind; +namespace fs = std::filesystem; + +struct Files { + Void::FileSystem::TempDir directory{"vls_bound_inputs_"}; + fs::path root = fs::canonical(directory.path()); + + fs::path path(std::string_view name) const { return root / name; } +}; + +void write(const fs::path &path, std::string_view text) { + std::ofstream output{path, std::ios::binary}; + output << text; + output.close(); + require(static_cast(output)); +} + +template +T get(std::expected result, + std::source_location loc = std::source_location::current()) { + require(result.has_value(), loc); + return std::move(*result); +} + +template +void expect_error(const std::expected &result, Kind kind, + std::source_location loc = std::source_location::current()) { + require(!result.has_value(), loc); + expect(result.error().kind == kind, loc); +} + +auto observe(const DocumentStore &store, const FileOverlayInventory &inventory, + const fs::path &path) { + return store.observe_bound_source(inventory, path_to_file_uri(path), path); +} + +auto replace(DocumentStore &store, std::string_view uri, std::int32_t version, std::string text) { + return store.apply_changes(uri, version, std::array{TextEdit{std::nullopt, std::move(text)}}); +} + +const FileOverlayBinding &binding(const FileOverlayInventory &inventory, std::string_view uri) { + const auto entries = inventory.entries(); + const auto found = std::ranges::find_if( + entries, [&](const auto &entry) { return entry.identity.canonical_uri == uri; }); + require(found != entries.end()); + return *found; +} +} // namespace + +VOID_TEST(BoundInputs, disk_snapshot_uses_caller_bytes_and_exact_bound_names) { + Files files; + const auto physical = files.path("one.cpp"); + const auto logical = files.path("other.cpp"); + write(physical, "ambient physical"); + write(logical, "ambient logical"); + const auto uri = path_to_file_uri(logical); + const auto display = "FILE://LOCALHOST" + uri.substr(7); + const std::string bytes = "a\U0001f600\r\nb"; + for (const auto encoding : {PositionEncoding::utf8, PositionEncoding::utf16}) { + unsigned ambient_reads = 0; + DocumentStore store{encoding, {}, [&] { ++ambient_reads; }}; + auto inventory = get(store.file_overlay_inventory(0)); + const auto observation = get(store.observe_bound_source(inventory, display, physical)); + expect(!observation.overlay()); + expect(observation.identity().canonical_uri == uri); + expect(observation.identity().display_uri == display); + expect(observation.identity().canonical_path == physical); + auto disk = get(store.materialize_bound_disk(observation, bytes)); + expect(disk->identity == observation.identity() && disk->text == bytes); + expect(disk->origin == DocumentOrigin::disk && !disk->version && + disk->encoding == encoding); + const auto column = encoding == PositionEncoding::utf8 ? 5u : 3u; + expect(disk->offset_to_position(5) == Position{0, column}); + expect(disk->position_to_offset({1, 0}) == 7); + auto again = get(store.materialize_bound_disk(observation, bytes)); + expect(again->revision_id != disk->revision_id && again->same_input_as(*disk)); + expect(!get(store.materialize_bound_disk(observation, "different"))->same_input_as(*disk)); + expect(get(store.materialize_bound_disk(observation, ""))->text.empty()); + expect(store.validate_bound_sources(inventory, std::array{observation}).has_value()); + expect(ambient_reads == 0); + expect(get(store.resolve_content(physical))->text == "ambient physical"); + expect(ambient_reads == 1); + } +} + +VOID_TEST(BoundInputs, empty_inventory_detects_a_new_unsaved_header) { + Files files; + const auto tu = files.path("main.cpp"); + const auto header = files.path("optional.hpp"); + const auto uri = path_to_file_uri(header); + DocumentStore store; + require(store.open("untitled:scratch", "cpp", 1, "virtual").has_value()); + const auto empty = get(store.file_overlay_inventory(0)); + require(empty.entries().empty()); + const auto disk = get(observe(store, empty, tu)); + const auto new_header = get(store.open(uri, "cpp", 1, "")); + expect(!fs::exists(header)); + expect_error(store.validate_bound_sources(empty), Kind::stale_read); + expect_error(observe(store, empty, tu), Kind::stale_read); + expect_error(store.materialize_bound_disk(disk, "old"), Kind::stale_read); + + const auto current = get(store.file_overlay_inventory(1)); + require(current.entries().size() == 1); + const auto &entry = binding(current, uri); + expect(entry.identity.canonical_path == header && entry.content == new_header); + const auto selected = get(observe(store, current, header)); + expect(selected.overlay() == new_header && selected.overlay()->text.empty()); + expect_error(store.materialize_bound_disk(selected, ""), Kind::already_open); + const auto current_tu = get(observe(store, current, tu)); + expect_error(store.validate_bound_sources(current, std::array{disk}), Kind::stale_read); + expect_error(store.validate_bound_sources(empty, std::array{current_tu}), Kind::stale_read); + expect(store.validate_bound_sources(current, std::array{current_tu, selected}).has_value()); +} + +VOID_TEST(BoundInputs, selection_uses_current_membership_and_per_document_revisions) { + Files files; + const auto a = files.path("early.cpp"); + const auto b = files.path("other.hpp"); + const auto early = path_to_file_uri(a); + const auto other = path_to_file_uri(b); + DocumentStore store; + const auto first = get(store.open(early, "cpp", 1, "early")); + const auto initial = get(store.file_overlay_inventory()); + const auto old_a = get(observe(store, initial, a)); + const auto second = get(store.open(other, "cpp", 1, "previous")); + require(first->overlay_epoch != second->overlay_epoch); + const auto census = get(store.file_overlay_inventory()); + const auto kept_a = get(observe(store, census, a)); + const auto kept_b = get(observe(store, census, b)); + expect(kept_a.overlay() == first); + expect(store.validate_bound_sources(census, std::array{kept_a, kept_b}).has_value()); + expect_error(store.validate_bound_sources(census, std::array{old_a}), Kind::stale_read); + + const auto updated = get(replace(store, other, 2, "previous")); + expect(store.validate_bound_sources(census, std::array{kept_a}).has_value()); + expect_error(store.validate_bound_sources(census, std::array{kept_a, kept_b}), + Kind::stale_read); + expect(binding(census, other).content == second); + const auto fresh_b = get(observe(store, census, b)); + expect(fresh_b.overlay() == updated && !updated->same_input_as(*second)); + expect(store.validate_bound_sources(census, std::array{kept_a, fresh_b}).has_value()); +} + +VOID_TEST(BoundInputs, open_edit_close_rejects_late_bytes_for_an_earlier_absence) { + Files files; + const auto source = files.path("main.cpp"); + const auto uri = path_to_file_uri(source); + DocumentStore store; + const auto initial = get(store.file_overlay_inventory()); + const auto absent = get(observe(store, initial, source)); + const auto before = get(store.materialize_bound_disk(absent, "same")); + require(store.open(uri, "cpp", 1, "open").has_value()); + expect_error(store.materialize_bound_disk(absent, "same"), Kind::stale_read); + require(replace(store, uri, 2, "changed").has_value()); + require(store.close(uri).has_value()); + expect_error(store.materialize_bound_disk(absent, "same"), Kind::stale_read); + const auto latest = get(store.file_overlay_inventory()); + expect_error(store.validate_bound_sources(latest, std::array{absent}), Kind::stale_read); + const auto now_absent = get(observe(store, latest, source)); + const auto after = get(store.materialize_bound_disk(now_absent, "same")); + expect(!after->same_input_as(*before)); +} + +VOID_TEST(BoundInputs, desynchronization_recovery_and_reopen_recheck_retained_overlays) { + Files files; + const auto path = files.path("edit.cpp"); + const auto uri = path_to_file_uri(path); + DocumentStore store; + const auto text = get(store.open(uri, "cpp", 7, "initial")); + const auto census = get(store.file_overlay_inventory()); + const auto original = get(observe(store, census, path)); + require(store.mark_desynchronized(uri, std::nullopt, {Kind::malformed_change, "bad range"}) + .has_value()); + expect_error(store.validate_bound_sources(census, std::array{original}), Kind::desynchronized); + expect_error(store.materialize_bound_disk(original, "disk"), Kind::desynchronized); + expect_error(observe(store, census, path), Kind::desynchronized); + const auto blocked = get(store.file_overlay_inventory()); + expect_error(binding(blocked, uri).content, Kind::desynchronized); + const auto recovered = get(replace(store, uri, 8, "initial")); + const auto fresh = get(observe(store, blocked, path)); + expect(fresh.overlay() == recovered && !recovered->same_input_as(*text)); + expect_error(store.validate_bound_sources(census, std::array{original}), Kind::stale_read); + require(store.close(uri).has_value()); + const auto reopened = get(store.open(uri, "cpp", 7, "initial")); + expect_error(store.validate_bound_sources(blocked, std::array{fresh}), Kind::stale_read); + expect(original.overlay() == text && original.overlay()->text == reopened->text); + expect(!original.overlay()->same_input_as(*reopened)); +} + +VOID_TEST(BoundInputs, refused_file_is_inventoried_and_cannot_be_materialized_from_disk) { + Files files; + const auto a = files.path("kept.cpp"); + const auto b = files.path("refused.cpp"); + const auto kept = path_to_file_uri(a); + const auto refused = path_to_file_uri(b); + DocumentStore store{PositionEncoding::utf16, + {.max_open_documents = 1, .max_unavailable_documents = 1}}; + const auto snapshot = get(store.open(kept, "cpp", 1, "editor")); + const auto before = get(store.file_overlay_inventory()); + const auto absent = get(observe(store, before, b)); + expect_error(store.open(refused, "cpp", 1, "refused bytes"), Kind::resource_limit); + expect_error(store.materialize_bound_disk(absent, "disk"), Kind::stale_read); + expect_error(store.file_overlay_inventory(1), Kind::resource_limit); + const auto census = get(store.file_overlay_inventory(2)); + require(census.entries().size() == 2); + expect(binding(census, kept).content == snapshot); + expect_error(binding(census, refused).content, Kind::unavailable_overlay); + expect_error(observe(store, census, b), Kind::unavailable_overlay); + require(store.mark_desynchronized(kept, 0, {Kind::invalid_range, "bad"}).has_value()); + const auto at_quota = get(store.file_overlay_inventory()); + expect_error(binding(at_quota, kept).content, Kind::desynchronized); + expect_error(binding(at_quota, refused).content, Kind::unavailable_overlay); + expect_error(replace(store, refused, 2, "still refused"), Kind::resource_limit); + require(store.close(kept).has_value()); + const auto room = get(store.file_overlay_inventory(1)); + expect_error(binding(room, refused).content, Kind::unavailable_overlay); + const auto restored = get(replace(store, refused, 3, "restored")); + expect(get(observe(store, room, b)).overlay() == restored); + expect(get(store.resolve_content(b)) == restored); +} + +VOID_TEST(BoundInputs, aliases_keep_their_client_keys_and_block_ambiguous_source_bytes) { + Files files; + fs::create_directories(files.path("real/sub")); + fs::create_directory_symlink(files.path("real/sub"), files.path("link")); + const auto physical = files.path("real/x.cpp"); + write(physical, "disk"); + const auto indirect = path_to_file_uri(files.path("link/../x.cpp")); + const auto direct = path_to_file_uri(physical); + DocumentStore store; + const auto first = get(store.open(indirect, "cpp", 1, "first")); + const auto old = get(store.file_overlay_inventory()); + const auto one = get(observe(store, old, physical)); + expect(one.identity().canonical_uri == direct && one.overlay() == first); + const auto indirect_view = get(store.observe_bound_source(old, indirect, physical)); + expect(indirect_view.identity().canonical_uri == indirect && indirect.contains("/link/../")); + const auto second = get(store.open(direct, "cpp", 1, "second")); + const auto both = get(store.file_overlay_inventory()); + require(both.entries().size() == 2); + for (const auto &key : {direct, indirect}) { + const auto &entry = binding(both, key); + expect(entry.identity.canonical_path == physical); + expect_error(entry.content, Kind::ambiguous_overlay); + expect_error(store.observe_bound_source(both, key, physical), Kind::ambiguous_overlay); + } + expect_error(store.validate_bound_sources(both, std::array{one}), Kind::stale_read); + expect(store.snapshot(indirect) == first && store.snapshot(direct) == second); + require(store.close(direct).has_value()); + expect(get(observe(store, get(store.file_overlay_inventory()), physical)).overlay() == first); +} + +VOID_TEST(BoundInputs, retargeted_lexical_key_cannot_supply_a_different_physical_source) { + Files files; + const auto a = files.path("a.cpp"); + const auto b = files.path("b.cpp"); + const auto link = files.path("alias.cpp"); + const auto uri = path_to_file_uri(link); + write(a, "disk a"); + write(b, "disk b"); + fs::create_symlink(a, link); + DocumentStore store; + const auto original = get(store.open(uri, "cpp", 1, "owned a")); + const auto census = get(store.file_overlay_inventory()); + const auto selected = get(store.observe_bound_source(census, uri, a)); + require(fs::remove(link)); + fs::create_symlink(b, link); + expect_error(store.observe_bound_source(census, uri, b), Kind::stale_read); + expect(get(observe(store, census, a)).overlay() == original); + expect(!get(observe(store, census, b)).overlay()); + // The store checks the supplied binding. The source catalog checks the changed disk name. + expect(get(store.observe_bound_source(census, uri, a)).overlay() == original); + expect(store.validate_bound_sources(census, std::array{selected}).has_value()); + require(store.close(uri).has_value()); + const auto next = get(store.file_overlay_inventory()); + expect(!get(store.observe_bound_source(next, uri, b)).overlay()); +} + +VOID_TEST(BoundInputs, virtual_marker_overflow_preserves_file_authority) { + Files files; + const auto a = files.path("open.cpp"); + const auto b = files.path("disk.cpp"); + const auto uri = path_to_file_uri(a); + DocumentStore store{PositionEncoding::utf16, + {.max_open_documents = 1, .max_unavailable_documents = 0}}; + const auto doc = get(store.open(uri, "cpp", 1, "overlay")); + const auto census = get(store.file_overlay_inventory()); + const auto active = get(observe(store, census, a)); + const auto absent = get(observe(store, census, b)); + expect_error(store.open("UnTiTled:Scratch", "cpp", 1, "virtual"), Kind::resource_limit); + expect(store.validate_bound_sources(census, std::array{active, absent}).has_value()); + const auto fresh = get(store.file_overlay_inventory(1)); + expect(binding(fresh, uri).content == doc); + expect(get(store.resolve_content(a)) == doc); + expect(get(store.materialize_bound_disk(absent, "disk"))->text == "disk"); + expect_error(store.close("untitled:Scratch"), Kind::not_open); + require(store.close(uri).has_value()); + expect(get(store.file_overlay_inventory(0)).entries().empty()); + expect(!store.set_position_encoding(PositionEncoding::utf8)); + const auto virtual_doc = get(store.open("untitled:Other", "cpp", 1, "virtual")); + expect(store.snapshot("untitled:Other") == virtual_doc); + require(store.close("untitled:Other").has_value()); +} + +VOID_TEST(BoundInputs, unrecorded_file_or_unclassifiable_open_withholds_file_authority) { + Files files; + const auto a = files.path("open.cpp"); + const auto b = files.path("future.hpp"); + const auto uri = path_to_file_uri(a); + for (const auto &[refused, reason] : + std::array{std::pair{path_to_file_uri(b), Kind::resource_limit}, + std::pair{std::string(kMaxDocumentUriBytes + 1, 'x'), Kind::resource_limit}, + std::pair{std::string{"no-scheme"}, Kind::invalid_uri}}) { + DocumentStore store{PositionEncoding::utf16, + {.max_open_documents = 1, .max_unavailable_documents = 0}}; + const auto doc = get(store.open(uri, "cpp", 1, "overlay")); + const auto census = get(store.file_overlay_inventory()); + const auto selected = get(observe(store, census, a)); + expect_error(store.open(refused, "cpp", 1, ""), reason); + expect_error(store.file_overlay_inventory(), Kind::unavailable_overlay); + expect_error(store.validate_bound_sources(census, std::array{selected}), Kind::stale_read); + expect(store.snapshot(uri) == doc); + require(store.close(uri).has_value()); + expect_error(store.file_overlay_inventory(), Kind::unavailable_overlay); + expect_error(store.resolve_content(b), Kind::unavailable_overlay); + } +} + +VOID_TEST(BoundInputs, unbound_file_blocks_inventory_until_its_client_key_closes) { + Files files; + const auto bad = path_to_file_uri(files.path("missing/../hidden.cpp")); + DocumentStore store; + const auto before = get(store.file_overlay_inventory()); + const auto open = get(store.open(bad, "cpp", 1, "unbound")); + require(open->identity.is_file_uri && open->identity.canonical_path.empty()); + expect_error(store.file_overlay_inventory(), Kind::unavailable_overlay); + expect_error(store.validate_bound_sources(before), Kind::stale_read); + require(store.close(bad).has_value()); + const auto restored = get(store.file_overlay_inventory(0)); + expect(!get(observe(store, restored, files.path("hidden.cpp"))).overlay()); +} + +VOID_TEST(BoundInputs, retained_inputs_reject_another_store_at_the_same_address) { + Files files; + const auto file = files.path("open.cpp"); + const auto disk = files.path("disk.cpp"); + const auto uri = path_to_file_uri(file); + std::optional store{std::in_place}; + const auto *address = &*store; + require(store->open(uri, "cpp", 1, "kept").has_value()); + const auto old = get(store->file_overlay_inventory()); + const auto active = get(observe(*store, old, file)); + const auto absent = get(observe(*store, old, disk)); + const auto snapshot = get(store->materialize_bound_disk(absent, "disk\nkept")); + store.reset(); + expect(active.overlay()->text == "kept" && binding(old, uri).content == active.overlay()); + expect(snapshot->line_index.line_count() == 2 && snapshot->text == "disk\nkept"); + store.emplace(); + require(&*store == address); + require(store->open(uri, "cpp", 1, "kept").has_value()); + const auto fresh = get(store->file_overlay_inventory()); + const auto new_active = get(observe(*store, fresh, file)); + require(new_active.overlay()->overlay_epoch == active.overlay()->overlay_epoch); + expect_error(store->validate_bound_sources(old), Kind::stale_read); + expect_error(observe(*store, old, disk), Kind::stale_read); + expect_error(store->materialize_bound_disk(absent, "disk"), Kind::stale_read); + expect_error(store->validate_bound_sources(fresh, std::array{active}), Kind::stale_read); + expect_error(store->validate_bound_sources(fresh, std::array{absent}), Kind::stale_read); + expect(store->validate_bound_sources(fresh, std::array{new_active}).has_value()); +} + +VOID_TEST(BoundInputs, disk_bytes_line_indexes_and_retained_snapshots_share_the_store_budget) { + Files files; + const auto path = files.path("large.cpp"); + const auto uri = path_to_file_uri(path); + DocumentStore store{PositionEncoding::utf8, + {.max_document_bytes = 6500, .max_snapshot_bytes = 8192}}; + { + const auto empty = get(store.file_overlay_inventory()); + const auto absent = get(observe(store, empty, path)); + expect_error(store.materialize_bound_disk(absent, std::string(6501, 'x')), + Kind::resource_limit); + expect_error(store.materialize_bound_disk(absent, "\xF0\x9F"), Kind::invalid_utf8); + expect_error(store.materialize_bound_disk(absent, std::string(2048, '\n')), + Kind::resource_limit); + std::string reserved = "tiny"; + reserved.reserve(8192); + expect_error(store.materialize_bound_disk(absent, std::move(reserved)), + Kind::resource_limit); + const auto kept = get(store.materialize_bound_disk(absent, std::string(6000, 'a'))); + expect_error(store.materialize_bound_disk(absent, std::string(6000, 'b')), + Kind::resource_limit); + expect_error(store.open(uri, "cpp", 1, std::string(6000, 'c')), Kind::resource_limit); + const auto refused = get(store.file_overlay_inventory()); + expect_error(binding(refused, uri).content, Kind::unavailable_overlay); + expect(kept->text.size() == 6000); + } + { + require(replace(store, uri, 2, std::string(6000, 'c')).has_value()); + const auto kept = get(store.file_overlay_inventory()); + require(store.close(uri).has_value()); + const auto empty = get(store.file_overlay_inventory()); + const auto absent = get(observe(store, empty, path)); + expect_error(store.materialize_bound_disk(absent, std::string(6000, 'a')), + Kind::resource_limit); + expect(binding(kept, uri).content.value()->text.size() == 6000); + } + const auto absent = get(observe(store, get(store.file_overlay_inventory()), path)); + expect(get(store.materialize_bound_disk(absent, std::string(6000, 'd')))->text.size() == 6000); +} + +VOID_TEST(BoundInputs, invalid_bound_names_and_encoding_changes_have_typed_outcomes) { + Files files; + const auto path = files.path("main.cpp"); + const auto uri = path_to_file_uri(path); + DocumentStore store; + const auto empty = get(store.file_overlay_inventory(0)); + for (const auto *bad : {"untitled:scratch", "broken", "file://remote/x.cpp", "file:///x%2Fy", + "file:///dir/", "file:///dir/.", "file:///dir/.."}) { + expect_error(store.observe_bound_source(empty, bad, path), Kind::invalid_uri); + } + for (const auto &bad : + {fs::path{}, fs::path{"relative"}, files.path("x/../main.cpp"), files.path("dir/"), + files.root / std::string{"a\0b", 3}, files.root / std::string{"bad\xFF"}}) { + expect_error(store.observe_bound_source(empty, uri, bad), Kind::invalid_uri); + } + expect_error( + store.observe_bound_source(empty, uri, files.root / std::string(kMaxDocumentUriBytes, 'x')), + Kind::resource_limit); + const auto absent = get(observe(store, empty, path)); + require(store.set_position_encoding(PositionEncoding::utf8)); + require(store.set_position_encoding(PositionEncoding::utf16)); + expect_error(store.validate_bound_sources(empty), Kind::stale_read); + expect_error(store.materialize_bound_disk(absent, ""), Kind::stale_read); +} diff --git a/tests/documents/DocumentTests.cpp b/tests/documents/DocumentTests.cpp new file mode 100644 index 0000000..927ae3f --- /dev/null +++ b/tests/documents/DocumentTests.cpp @@ -0,0 +1,629 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#endif + +namespace { + +using namespace Void::LanguageServer::Documents; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +using ErrorKind = DocumentError::Kind; +constexpr auto utf8 = PositionEncoding::utf8; +constexpr auto utf16 = PositionEncoding::utf16; +constexpr std::string_view virtual_uri = "untitled:document.cpp"; + +template +void expect_error(const std::expected &result, ErrorKind kind, + std::source_location location = std::source_location::current()) { + require(!result.has_value(), location); + expect_eq(result.error().kind, kind, location); +} + +template +T get(std::expected result, + std::source_location location = std::source_location::current()) { + require(result.has_value(), location); + return std::move(*result); +} + +TextEdit full(std::string text) { return TextEdit{std::nullopt, std::move(text)}; } + +TextEdit edit(Position start, Position end, std::string text) { + return TextEdit{Range{start, end}, std::move(text)}; +} + +#ifndef _WIN32 +class TestDirectory { + public: + TestDirectory() { + auto pattern = (std::filesystem::temp_directory_path() / "vls-documents-XXXXXX").string(); + const auto *created = ::mkdtemp(pattern.data()); + require(created != nullptr); + path_ = created; + } + + TestDirectory(const TestDirectory &) = delete; + TestDirectory &operator=(const TestDirectory &) = delete; + + ~TestDirectory() { + std::error_code error; + std::filesystem::remove_all(path_, error); + } + + std::filesystem::path path(std::string_view name) const { return path_ / name; } + + private: + std::filesystem::path path_; +}; + +void write_file(const std::filesystem::path &path, std::string_view text) { + std::ofstream file{path, std::ios::binary}; + file.write(text.data(), static_cast(text.size())); + file.close(); + require(static_cast(file)); +} +#endif + +bool matches_fresh_index(const DocumentSnapshot &snapshot) { + const LineIndex fresh{snapshot.text}; + if (fresh.line_count() != snapshot.line_index.line_count()) { + return false; + } + for (std::uint32_t line = 0; line < fresh.line_count(); ++line) { + if (fresh.line_start_offset(line) != snapshot.line_index.line_start_offset(line)) { + return false; + } + } + for (std::size_t offset = 0; offset <= snapshot.text.size(); ++offset) { + if (fresh.offset_to_position(snapshot.text, offset, snapshot.encoding) != + snapshot.offset_to_position(offset)) { + return false; + } + } + return true; +} + +} // namespace + +VOID_TEST(Documents, positions_round_trip_and_clamp_in_both_encodings) { + constexpr std::string_view text = "a\u0301\U0001F600\r\n\u03B2\rz\n"; + const LineIndex index{text}; + struct Boundary { + std::size_t byte; + Position utf8_position; + Position utf16_position; + }; + constexpr std::array boundaries{ + Boundary{0, {0, 0}, {0, 0}}, Boundary{1, {0, 1}, {0, 1}}, Boundary{3, {0, 3}, {0, 2}}, + Boundary{7, {0, 7}, {0, 4}}, Boundary{9, {1, 0}, {1, 0}}, Boundary{11, {1, 2}, {1, 1}}, + Boundary{12, {2, 0}, {2, 0}}, Boundary{13, {2, 1}, {2, 1}}, Boundary{14, {3, 0}, {3, 0}}, + }; + for (const auto &point : boundaries) { + expect(index.position_to_offset(text, point.utf8_position, utf8) == point.byte); + expect(index.position_to_offset(text, point.utf16_position, utf16) == point.byte); + expect(index.offset_to_position(text, point.byte, utf8) == point.utf8_position); + expect(index.offset_to_position(text, point.byte, utf16) == point.utf16_position); + } + for (const auto encoding : {utf8, utf16}) { + expect(index.position_to_offset(text, {0, kMaxPositionValue}, encoding) == 7); + expect(index.position_to_offset(text, {1, 800}, encoding) == 11); + expect(index.position_to_offset(text, {3, 800}, encoding) == text.size()); + expect(!index.position_to_offset(text, {4, 0}, encoding)); + expect(!index.position_to_offset(text, {0, kMaxPositionValue + 1}, encoding)); + expect(!index.offset_to_position(text, text.size() + 1, encoding)); + expect(!index.offset_to_position(text, 8, encoding)); + expect(index.range_to_offsets(text, {{0, 99}, {1, 0}}, encoding) == + std::pair{7, 9}); + expect(!index.range_to_offsets(text, {{1, 0}, {0, 99}}, encoding)); + for (const auto split : {2U, 4U, 5U, 6U, 10U}) { + expect(!index.offset_to_position(text, split, encoding)); + } + } + expect(!index.position_to_offset(text, {0, 2}, utf8)); + expect(!index.position_to_offset(text, {0, 5}, utf8)); + expect(!index.position_to_offset(text, {0, 3}, utf16)); + expect(!index.line_start_offset(4)); + expect(!index.line_content_end_offset(text, 4)); + expect(!index.line_content_end_offset("different", 0)); +} + +VOID_TEST(Documents, empty_text_and_truncated_utf8_have_safe_boundaries) { + const LineIndex empty{""}; + expect_eq(empty.line_count(), std::size_t{1}); + expect(empty.position_to_offset("", {0, kMaxPositionValue}, utf16) == 0); + expect(empty.offset_to_position("", 0, utf8) == Position{0, 0}); + expect(!empty.offset_to_position("", 1, utf8)); + + const std::string truncated{"\xF0\x9F"}; + const LineIndex broken{truncated}; + expect(!broken.position_to_offset(truncated, {0, 900}, utf8)); + expect(!broken.position_to_offset(truncated, {0, 900}, utf16)); + expect(!broken.offset_to_position(truncated, truncated.size(), utf16)); + + DocumentStore store; + expect_error(store.open(virtual_uri, "cpp", 1, truncated), ErrorKind::invalid_utf8); + expect(!store.snapshot(virtual_uri)); + auto restored = get(store.apply_changes(virtual_uri, 2, std::array{full("")})); + expect(restored->position_to_offset({0, kMaxPositionValue}) == 0); + expect(restored->version == 2); +} + +VOID_TEST(Documents, virtual_and_file_uri_spellings_are_validated) { + const auto item = normalize_uri("VoId-GeNeRaTeD://host/unit%2Fpart#range"); + require(item.has_value()); + expect_eq(item->canonical_uri, std::string{"void-generated://host/unit%2Fpart#range"}); + expect_eq(item->display_uri, std::string{"VoId-GeNeRaTeD://host/unit%2Fpart#range"}); + expect(!item->is_file_uri && item->canonical_path.empty()); + expect(client_uri_key("void-generated://host/unit/part#range") != item->canonical_uri); + for (const auto invalid : + {"no-scheme", "3untitled:x", "untitled:", "untitled:a b", "untitled:x%00y", + "untitled:x%ZZ", "file:relative", "file://remote/path", "file:////unc/path", + "file:///x%2Fy", "file:///x%5cy", "file:///x%00y", "file:///x%FF", "file:///trailing%", + "file:///x?query", "file:///x#fragment", "file:///x\\y"}) { + expect(!normalize_uri(invalid)); + } + expect(!normalize_uri(std::string_view{"untitled:a\0b", 12})); + expect(!identity_from_path(std::filesystem::path{std::string{"/a\0b", 4}})); + + DocumentStore store; + auto snapshot = get(store.open("UNTITLED:Scratch", "cpp", -3, "virtual")); + expect_eq(snapshot->identity.display_uri, std::string{"UNTITLED:Scratch"}); + expect(store.snapshot("untitled:Scratch") == snapshot); + expect(!store.snapshot("untitled:scratch")); + require(store.close("untitled:Scratch").has_value()); +} + +VOID_TEST(Documents, ordered_edits_preserve_prior_snapshot_text_and_positions) { + DocumentStore store; + auto original = get(store.open(virtual_uri, "cpp", 5, "a\r\nb\n")); + const std::array edits{ + edit({0, 1}, {0, 1}, "\u0301\U0001F600"), + edit({0, 4}, {1, 0}, "\r"), + edit({1, 0}, {1, 0}, "\n"), + edit({1, 400}, {1, 400}, "!"), + }; + auto changed = get(store.apply_changes(virtual_uri, 6, edits)); + expect_eq(changed->text, std::string{"a\u0301\U0001F600\r\nb!\n"}); + expect(changed->version == 6 && changed->revision_id > original->revision_id); + expect(changed->origin == DocumentOrigin::overlay && !changed->same_input_as(*original)); + expect(matches_fresh_index(*changed)); + expect(store.snapshot(virtual_uri) == changed); + + expect_eq(original->text, std::string{"a\r\nb\n"}); + expect(original->version == 5 && original->position_to_offset({1, 0}) == 3); + require(store.close(virtual_uri).has_value()); + expect(!store.snapshot(virtual_uri)); + expect_eq(changed->text, std::string{"a\u0301\U0001F600\r\nb!\n"}); +} + +VOID_TEST(Documents, edited_line_index_matches_rebuild_across_crlf_splices) { + DocumentStore store{utf8}; + constexpr std::array inputs{ + "", "x", "\r", "\n", "\r\n", "\r\r\n", "x\r\ny\nz\rt", "x\r\U0001F600\n", "\rxx\n"}; + constexpr std::array replacements{"", "y", "\r", "\n", + "\r\n", "\n\r", "\rhello\n", "\U0001F600"}; + for (const std::string_view input : inputs) { + const LineIndex base{input}; + for (std::size_t begin = 0; begin <= input.size(); ++begin) { + const auto start = base.offset_to_position(input, begin, utf8); + if (!start) { + continue; + } + for (std::size_t end = begin; end <= input.size(); ++end) { + const auto stop = base.offset_to_position(input, end, utf8); + if (!stop) { + continue; + } + for (const std::string_view replacement : replacements) { + require(store.open(virtual_uri, "cpp", 0, std::string{input}).has_value()); + const std::array edits{edit(*start, *stop, std::string{replacement})}; + const auto changed = get(store.apply_changes(virtual_uri, 1, edits)); + auto expected_text = std::string{input}; + expected_text.replace(begin, end - begin, replacement); + expect_eq(changed->text, expected_text); + expect(matches_fresh_index(*changed)); + require(store.close(virtual_uri).has_value()); + } + } + } + } +} + +VOID_TEST(Documents, failed_batch_has_no_partial_publication_and_requires_a_newer_replacement) { + DocumentStore store; + auto original = get(store.open(virtual_uri, "cpp", 8, "base\n")); + const std::array invalid{full("unpublished"), edit({3, 0}, {3, 0}, "!")}; + expect_error(store.apply_changes(virtual_uri, 12, invalid), ErrorKind::invalid_range); + expect(!store.snapshot(virtual_uri) && store.list_overlays().empty()); + expect_eq(original->text, std::string{"base\n"}); + expect(original->version == 8 && original->position_to_offset({1, 0}) == 5); + expect_error(store.apply_changes(virtual_uri, 10, std::array{full("stale")}), + ErrorKind::nonmonotonic_version); + expect(!store.snapshot(virtual_uri)); + expect_error(store.open(virtual_uri, "cpp", 13, "duplicate"), ErrorKind::already_open); + + const std::array recovery{full("a\U0001F600"), edit({0, 3}, {0, 3}, "!")}; + auto restored = get(store.apply_changes(virtual_uri, 13, recovery)); + expect(restored->version == 13); + expect_eq(restored->text, std::string{"a\U0001F600!"}); + expect(restored->revision_id > original->revision_id); + require(store.close(virtual_uri).has_value()); + + auto reopened = get(store.open(virtual_uri, "cpp", -20, "base\n")); + expect(reopened->version == -20 && reopened->revision_id > restored->revision_id); + expect(!reopened->same_input_as(*original)); + expect(reopened->content_hash == original->content_hash); +} + +VOID_TEST(Documents, malformed_and_stale_notifications_discard_readiness) { + DocumentStore store; + const auto min_version = std::numeric_limits::min(); + auto original = get(store.open(virtual_uri, "cpp", min_version, "initial")); + expect(original->version == min_version); + require(store + .mark_desynchronized(virtual_uri, std::nullopt, + {ErrorKind::malformed_change, "missing version"}) + .has_value()); + expect(!store.snapshot(virtual_uri)); + require(store.apply_changes(virtual_uri, 8, std::array{full("current")}).has_value()); + require(store + .mark_desynchronized("UNTITLED:document.cpp", 6, + {ErrorKind::malformed_change, "malformed range"}) + .has_value()); + expect(!store.snapshot(virtual_uri)); + expect_error(store.apply_changes(virtual_uri, 7, std::array{full("late")}), + ErrorKind::nonmonotonic_version); + require( + store.mark_desynchronized(virtual_uri, 12, {ErrorKind::malformed_change, "invalid event"}) + .has_value()); + expect_error(store.apply_changes(virtual_uri, 10, std::array{full("late")}), + ErrorKind::nonmonotonic_version); + require(store.apply_changes(virtual_uri, 13, std::array{full("ready")}).has_value()); + + constexpr auto invalid_version = std::int64_t{std::numeric_limits::max()} + 1; + expect_error(store.apply_changes(virtual_uri, invalid_version, std::array{full("invalid")}), + ErrorKind::invalid_version); + expect(!store.snapshot(virtual_uri)); + require(store.apply_changes(virtual_uri, 14, std::array{full("ready again")}).has_value()); + expect_error(store.open("untitled:bad-version", "cpp", invalid_version, ""), + ErrorKind::invalid_version); + expect_error( + store.mark_desynchronized("untitled:unknown", 15, {ErrorKind::malformed_change, "unknown"}), + ErrorKind::not_open); +} + +VOID_TEST(Documents, change_count_aggregate_text_and_document_size_are_bounded) { + DocumentStore store{utf16, {.max_document_bytes = 8, .max_changes = 2, .max_change_bytes = 11}}; + expect_error(store.open(virtual_uri, "cpp", 1, "123456789"), ErrorKind::resource_limit); + expect(!store.snapshot(virtual_uri)); + auto original = get(store.apply_changes(virtual_uri, 2, std::array{full("12345678")})); + const std::array too_many{full("a"), full("b"), full("c")}; + expect_error(store.apply_changes(virtual_uri, 3, too_many), ErrorKind::resource_limit); + const std::array too_many_bytes{full("12345678"), full("1234")}; + expect_error(store.apply_changes(virtual_uri, 4, too_many_bytes), ErrorKind::resource_limit); + const std::array too_large{full("12345678"), edit({0, 8}, {0, 8}, "9")}; + expect_error(store.apply_changes(virtual_uri, 5, too_large), ErrorKind::resource_limit); + expect(!store.snapshot(virtual_uri)); + expect_eq(original->text, std::string{"12345678"}); + require(store.apply_changes(virtual_uri, 6, std::array{full("recovery")}).has_value()); +} + +#ifndef _WIN32 +VOID_TEST(Documents, prospective_names_preserve_the_actual_parent_traversal) { + namespace fs = std::filesystem; + TestDirectory temp; + write_file(temp.path("x.cpp"), "int actual;\n"); + fs::create_symlink("absent", temp.path("dangling")); + fs::create_directories(temp.path("real/sub")); + fs::create_directory_symlink("real/sub", temp.path("link")); + for (const auto *name : + {"absent/../x.cpp", "dangling/../x.cpp", "x.cpp/../x.cpp", "dangling"}) { + const auto uri = path_to_file_uri(temp.path(name)); + auto identity = normalize_uri(uri); + require(identity.has_value()); + expect(identity->is_file_uri && identity->canonical_path.empty()); + expect(client_file_path(uri) == temp.path(name)); + } + const auto name = temp.path("link/../new/child.cpp"); + auto future = identity_from_path(name); + require(future.has_value()); + expect(future->canonical_path == temp.path("real/new/child.cpp")); +} + +VOID_TEST(Documents, file_aliases_preserve_client_binding_and_reject_ambiguous_lookup) { + TestDirectory temp; + const auto a = temp.path("first file#.cpp"); + const auto b = temp.path("other.cpp"); + const auto alias = temp.path("link.cpp"); + write_file(a, "first disk"); + write_file(b, "other disk"); + std::filesystem::create_symlink(a, alias); + const auto a_uri = path_to_file_uri(a); + const auto a_alt = "FILE://LOCALHOST" + a_uri.substr(7); + const auto alias_uri = path_to_file_uri(alias); + const auto a_identity = normalize_uri(a_alt); + const auto alias_identity = normalize_uri(alias_uri); + require(a_identity.has_value() && alias_identity.has_value()); + expect_eq(a_identity->canonical_uri, a_uri); + expect(a_identity->canonical_uri.contains("first%20file%23.cpp")); + expect(a_identity->canonical_path == alias_identity->canonical_path); + expect(a_identity->canonical_uri != alias_identity->canonical_uri); + expect(client_uri_key("file:" + a_uri.substr(7)) == a_uri); + + DocumentStore store; + auto first = get(store.open(a_alt, "cpp", 1, "first overlay")); + expect_eq(first->identity.display_uri, a_alt); + expect(store.snapshot(a_uri) == first); + expect(get(store.resolve_content(alias, 1)) == first); + expect_error(store.open(a_uri, "cpp", 2, "same lexical document"), ErrorKind::already_open); + auto second = get(store.open(alias_uri, "cpp", 1, "second overlay")); + expect(store.snapshot(alias_uri) == second); + expect_error(store.resolve_content(a), ErrorKind::ambiguous_overlay); + expect(!store.snapshot_by_path(a)); + + require(std::filesystem::remove(alias)); + std::filesystem::create_symlink(b, alias); + expect(store.snapshot(alias_uri) == second); + expect_error(store.resolve_content(alias), ErrorKind::stale_read); + expect_eq(get(store.resolve_content(b))->text, std::string{"other disk"}); + auto updated = get(store.apply_changes(alias_uri, 2, std::array{full("bound to original")})); + expect(updated->identity.canonical_path == first->identity.canonical_path); + require(store.close(alias_uri).has_value()); + expect(get(store.resolve_content(a)) == first); + expect_eq(get(store.resolve_content(alias))->text, std::string{"other disk"}); +} + +VOID_TEST(Documents, dot_segments_are_resolved_after_symlinks) { + TestDirectory temp; + const auto a = temp.path("a"); + const auto b = temp.path("b"); + std::filesystem::create_directory(a); + std::filesystem::create_directories(b / "inner"); + write_file(a / "test.cpp", "a"); + write_file(b / "test.cpp", "b"); + std::filesystem::create_symlink(b / "inner", a / "link"); + const auto indirect = a / "link" / ".." / "test.cpp"; + const auto indirect_uri = path_to_file_uri(indirect); + const auto direct_uri = path_to_file_uri(a / "test.cpp"); + DocumentStore store; + auto opened = get(store.open(indirect_uri, "cpp", 1, "open b")); + expect(opened->identity.canonical_uri.contains("/link/../")); + expect(get(store.resolve_content(b / "test.cpp")) == opened); + expect_eq(get(store.resolve_content(a / "test.cpp"))->text, std::string{"a"}); + expect(!store.snapshot(direct_uri)); +} + +VOID_TEST(Documents, disk_reads_are_typed_bounded_and_have_stable_input_identity) { + TestDirectory temp; + const auto source = temp.path("disk.cpp"); + const auto missing = temp.path("missing.cpp"); + const auto invalid = temp.path("invalid.cpp"); + const auto fifo = temp.path("named-pipe"); + write_file(source, "disk"); + write_file(invalid, "\xF0\x9F"); + require(::mkfifo(fifo.c_str(), 0600) == 0); + DocumentStore store{utf16, {.max_document_bytes = 4}}; + expect_error(store.resolve_content(missing), ErrorKind::disk_read_failed); + expect_error(store.resolve_content(temp.path("")), ErrorKind::disk_read_failed); + expect_error(store.resolve_content(fifo), ErrorKind::disk_read_failed); + expect_error(store.resolve_content(invalid), ErrorKind::invalid_utf8); + expect_error(store.resolve_content(source, 3), ErrorKind::resource_limit); + auto first = get(store.resolve_content(source)); + auto second = get(store.resolve_content(source)); + expect(first->origin == DocumentOrigin::disk && !first->version); + expect(second->revision_id != first->revision_id && second->same_input_as(*first)); + expect(first->same_input_as(*second)); + + const auto alias = temp.path("disk-link.cpp"); + std::filesystem::create_symlink(source, alias); + expect(get(store.resolve_content(alias))->same_input_as(*first)); + write_file(source, "edit"); + expect(!get(store.resolve_content(source))->same_input_as(*first)); + write_file(source, "disks"); + expect_error(store.resolve_content(source, 1000), ErrorKind::resource_limit); + write_file(source, "disk"); + const auto uri = path_to_file_uri(source); + auto overlay = get(store.open(uri, "cpp", 1, "disk")); + expect(!overlay->same_input_as(*first)); + require(store.close(uri).has_value()); + auto after_close = get(store.resolve_content(source)); + expect(!after_close->same_input_as(*first) && + after_close->overlay_epoch > first->overlay_epoch); +} + +VOID_TEST(Documents, snapshot_budget_counts_retained_references_and_saves_desync_state) { + TestDirectory temp; + const auto first = temp.path("first.cpp"); + const auto second = temp.path("second.cpp"); + write_file(first, "first disk"); + write_file(second, "second disk"); + const auto first_uri = path_to_file_uri(first); + const auto second_uri = path_to_file_uri(second); + DocumentStore store{utf16, {.max_snapshot_bytes = 8 * 1024}}; + const std::string large{std::string(6 * 1024, 'x')}; + auto kept = get(store.open(first_uri, "cpp", 1, large)); + require(store.mark_desynchronized(first_uri, 12, {ErrorKind::malformed_change, "bad late edit"}) + .has_value()); + expect_error(store.resolve_content(first), ErrorKind::desynchronized); + expect_error(store.apply_changes(first_uri, 10, std::array{full("stale")}), + ErrorKind::nonmonotonic_version); + require(store.close(first_uri).has_value()); + expect_error(store.open(second_uri, "cpp", 1, large), ErrorKind::resource_limit); + expect_error(store.resolve_content(second), ErrorKind::unavailable_overlay); + expect_eq(kept->text, large); + expect(kept->position_to_offset({0, 9000}) == large.size()); + + kept.reset(); + auto restored = get(store.apply_changes(second_uri, 2, std::array{full(large)})); + expect(store.snapshot_by_path(second) == restored); + expect(restored->version == 2); + require(store.close(second_uri).has_value()); + restored.reset(); + expect_error(store.open(first_uri, "cpp", 1, std::string(2048, '\n')), + ErrorKind::resource_limit); + expect_error(store.resolve_content(first), ErrorKind::unavailable_overlay); +} + +VOID_TEST(Documents, refused_open_owns_its_content_and_marker_overflow_fails_closed) { + TestDirectory temp; + const auto a = temp.path("a.cpp"); + const auto b = temp.path("b.cpp"); + const auto c = temp.path("c.cpp"); + write_file(a, "disk a"); + write_file(b, "disk b"); + write_file(c, "disk c"); + const auto a_uri = path_to_file_uri(a); + const auto b_uri = path_to_file_uri(b); + const auto c_uri = path_to_file_uri(c); + DocumentStore store{utf16, {.max_open_documents = 1, .max_unavailable_documents = 1}}; + auto a_snapshot = get(store.open(a_uri, "cpp", 1, "overlay a")); + expect_error(store.open(b_uri, "cpp", 1, "overlay b"), ErrorKind::resource_limit); + expect_error(store.resolve_content(b), ErrorKind::unavailable_overlay); + expect_error(store.open(c_uri, "cpp", 1, "overlay c"), ErrorKind::resource_limit); + expect_error(store.resolve_content(c), ErrorKind::unavailable_overlay); + expect(store.snapshot(a_uri) == a_snapshot); + require(store.close(b_uri).has_value()); + require(store.close(a_uri).has_value()); + expect_error(store.resolve_content(c), ErrorKind::unavailable_overlay); + expect_error(store.resolve_content(a), ErrorKind::unavailable_overlay); + expect_eq(get(DocumentStore{}.resolve_content(c))->text, std::string{"disk c"}); +} + +VOID_TEST(Documents, late_open_wins_over_successful_and_failed_disk_reads) { + TestDirectory temp; + const auto existing = temp.path("existing.cpp"); + const auto missing = temp.path("missing.cpp"); + const auto invalid = temp.path("invalid.cpp"); + write_file(existing, "disk input"); + write_file(invalid, "\xF0\x9F"); + for (const auto &path : {existing, missing, invalid}) { + const auto uri = path_to_file_uri(path); + unsigned callbacks = 0; + DocumentStore store{utf16, {}, [&] { + ++callbacks; + require(store.open(uri, "cpp", 1, "new overlay").has_value()); + }}; + auto result = get(store.resolve_content(path)); + expect_eq(callbacks, 1U); + expect_eq(result->text, std::string{"new overlay"}); + expect(result == store.snapshot(uri)); + } +} + +VOID_TEST(Documents, late_unavailable_and_desynchronized_opens_preempt_disk) { + TestDirectory temp; + const auto path = temp.path("real.cpp"); + write_file(path, "old text"); + const auto uri = path_to_file_uri(path); + DocumentStore refused{utf16, {.max_open_documents = 0}, [&] { + expect_error(refused.open(uri, "cpp", 1, "overlay"), + ErrorKind::resource_limit); + }}; + expect_error(refused.resolve_content(path), ErrorKind::unavailable_overlay); + + DocumentStore broken{ + utf16, {}, [&] { + require(broken.open(uri, "cpp", 1, "overlay").has_value()); + require(broken.mark_desynchronized(uri, 2, {ErrorKind::malformed_change, "bad field"}) + .has_value()); + }}; + expect_error(broken.resolve_content(path), ErrorKind::desynchronized); +} + +VOID_TEST(Documents, open_close_aba_rejects_old_success_and_error) { + TestDirectory temp; + const auto existing = temp.path("exists.cpp"); + const auto missing = temp.path("missing.cpp"); + write_file(existing, "disk text"); + for (const auto &path : {existing, missing}) { + const auto uri = path_to_file_uri(path); + unsigned callbacks = 0; + DocumentStore store{utf16, {}, [&] { + ++callbacks; + require(store.open(uri, "cpp", 1, "transient").has_value()); + require(store.close(uri).has_value()); + }}; + expect_error(store.resolve_content(path), ErrorKind::stale_read); + expect_eq(callbacks, 1U); + expect(!store.snapshot(uri)); + } +} + +VOID_TEST(Documents, mid_read_modification_and_late_replacement_are_stale) { + namespace Files = Void::LanguageServer::Detail; + TestDirectory temp; + const auto file = temp.path("edited.cpp"); + const std::string original(160 * 1024, 'a'); + const std::string changed(original.size(), 'b'); + write_file(file, original); + bool replaced = false; + const auto read = Files::read_regular(file, original.size(), false, [&](auto chunk) { + if (!replaced) { + require(chunk.size() < original.size()); + write_file(file, changed); + // Force a distinct timestamp even on a filesystem with coarse resolution. + std::filesystem::last_write_time(file, std::filesystem::last_write_time(file) - + std::chrono::seconds{5}); + replaced = true; + } + return true; + }); + require(replaced); + expect(!read && read.error() == Files::FileError::changed); + + DocumentStore store{utf16, {}, [&] { + const auto next = temp.path("replacement.cpp"); + write_file(next, original); + std::filesystem::rename(next, file); + }}; + expect_error(store.resolve_content(file), ErrorKind::stale_read); + expect(get(DocumentStore{}.resolve_content(file))->text == original); +} + +VOID_TEST(Documents, disk_reads_revalidate_path_and_encoding_before_return) { + TestDirectory temp; + const auto before = temp.path("before.cpp"); + const auto after = temp.path("after.cpp"); + const auto link = temp.path("link.cpp"); + write_file(before, "before"); + write_file(after, "after"); + std::filesystem::create_symlink(before, link); + DocumentStore moved{utf16, {}, [&] { + require(std::filesystem::remove(link)); + std::filesystem::create_symlink(after, link); + }}; + expect_error(moved.resolve_content(link), ErrorKind::stale_read); + + unsigned callbacks = 0; + DocumentStore negotiation{utf16, {}, [&] { + if (++callbacks == 1) { + require(negotiation.set_position_encoding(utf8)); + } + }}; + expect_error(negotiation.resolve_content(after), ErrorKind::stale_read); + expect(get(negotiation.resolve_content(after))->encoding == utf8); + auto open = get(negotiation.open(path_to_file_uri(after), "cpp", 1, "text")); + expect(!negotiation.set_position_encoding(utf16)); + expect(negotiation.position_encoding() == utf8 && open->encoding == utf8); +} +#endif diff --git a/tests/documents/LongLineTests.cpp b/tests/documents/LongLineTests.cpp new file mode 100644 index 0000000..941a613 --- /dev/null +++ b/tests/documents/LongLineTests.cpp @@ -0,0 +1,139 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace Void::LanguageServer::Documents; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +constexpr auto utf8 = PositionEncoding::utf8; +constexpr auto utf16 = PositionEncoding::utf16; +constexpr std::uint32_t line_bytes = 64 * 1024; +constexpr std::uint32_t pivot = line_bytes / 2 - 1; +constexpr std::string_view uri = "untitled:long-line.cpp"; +constexpr auto astral = "\U0001F600"; + +} // namespace + +VOID_TEST(LongLines, ascii_endpoints_clamp_and_text_size_stays_checked) { + const auto text = std::string(line_bytes, 'a') + "\r\nz"; + const auto shorter = std::string_view{text}.substr(0, text.size() - 1); + const LineIndex index{text}; + for (const auto encoding : {utf8, utf16}) { + expect(index.range_to_offsets(text, {{0, 2}, {0, 3}}, encoding) == + std::pair{2, 3}); + expect( + index.range_to_offsets(text, {{0, line_bytes - 3}, {0, kMaxPositionValue}}, encoding) == + std::pair{line_bytes - 3, line_bytes}); + expect(index.range_to_offsets(text, {{0, line_bytes + 1}, {1, 0}}, encoding) == + std::pair{line_bytes, line_bytes + 2}); + expect(index.offset_to_position(text, line_bytes, encoding) == Position{0, line_bytes}); + expect(!index.offset_to_position(text, line_bytes + 1, encoding)); + expect(!index.offset_to_position(text, text.size() + 1, encoding)); + expect(!index.position_to_offset(text, {kMaxPositionValue + 1, 0}, encoding)); + expect(!index.position_to_offset(text, {0, kMaxPositionValue + 1}, encoding)); + expect( + !index.range_to_offsets(text, {{0, line_bytes}, {0, kMaxPositionValue + 1}}, encoding)); + expect(!index.range_to_offsets(text, {{0, line_bytes}, {0, 2}}, encoding)); + expect(!index.position_to_offset(shorter, {0, 2}, encoding)); + expect(!index.offset_to_position(shorter, 2, encoding)); + expect(!index.range_to_offsets(shorter, {{0, 2}, {0, 3}}, encoding)); + } +} + +VOID_TEST(LongLines, mixed_ascii_and_unicode_ranges_check_both_endpoints) { + auto text = std::string(pivot, 'a') + "\u03B2" + astral; + text.append(line_bytes - pivot, 'b'); + const LineIndex index{text}; + for (const auto encoding : {utf8, utf16}) { + const auto astral_start = pivot + (encoding == utf8 ? 2 : 1); + const auto end = line_bytes + (encoding == utf8 ? 6 : 3); + expect(index.range_to_offsets(text, {{0, astral_start}, {0, end}}, encoding) == + std::pair{pivot + 2, text.size()}); + expect(index.position_to_offset(text, {0, kMaxPositionValue}, encoding) == text.size()); + expect(index.offset_to_position(text, text.size(), encoding) == Position{0, end}); + + const auto split = astral_start + 1; + expect(!index.range_to_offsets(text, {{0, pivot}, {0, split}}, encoding)); + expect(!index.range_to_offsets(text, {{0, split}, {0, end}}, encoding)); + expect(!index.offset_to_position(text, pivot + 3, encoding)); + } +} + +VOID_TEST(LongLines, invalid_utf8_after_an_ascii_run_is_still_rejected) { + for (const std::string_view suffix : {"\x80", "\xF0\x9F"}) { + const auto text = std::string(pivot, 'a') + std::string{suffix}; + const LineIndex index{text}; + for (const auto encoding : {utf8, utf16}) { + expect(index.position_to_offset(text, {0, pivot}, encoding) == pivot); + const auto range = + index.range_to_offsets(text, {{0, pivot - 1}, {0, kMaxPositionValue}}, encoding); + require(!range.has_value()); + expect_eq(range.error(), std::string{"invalid UTF-8 encountered on line"}); + expect(!index.offset_to_position(text, text.size(), encoding)); + } + } +} + +VOID_TEST(LongLines, edits_insert_remove_and_rebuild_unicode_positions) { + const std::string ascii(line_bytes, 'a'); + for (const auto encoding : {utf8, utf16}) { + DocumentStore store{encoding}; + const auto original = store.open(uri, "cpp", 1, ascii); + require(original.has_value()); + + const auto scalar_units = encoding == utf8 ? 4U : 2U; + const auto after_scalar = pivot + scalar_units; + const std::array adding{ + TextEdit{Range{{0, pivot}, {0, pivot + 1}}, astral}, + TextEdit{Range{{0, after_scalar}, {0, after_scalar + 1}}, "x"}, + }; + const auto mixed = store.apply_changes(uri, 2, adding); + require(mixed.has_value()); + auto expected_mixed = ascii; + expected_mixed.replace(pivot, 2, std::string{astral} + "x"); + expect_eq((*mixed)->text, expected_mixed); + expect((*mixed)->position_to_offset({0, after_scalar + 1}) == pivot + 5); + + const std::array removing{ + TextEdit{Range{{0, pivot}, {0, after_scalar}}, "a"}, + TextEdit{Range{{0, pivot + 1}, {0, pivot + 2}}, "a"}, + }; + const auto restored = store.apply_changes(uri, 3, removing); + require(restored.has_value()); + expect_eq((*restored)->text, ascii); + expect((*restored)->position_to_offset({0, kMaxPositionValue}) == line_bytes); + + const std::array rebuilding{ + TextEdit{std::nullopt, ascii + "\r" + astral + "a"}, + TextEdit{Range{{1, 0}, {1, 0}}, "\n"}, + TextEdit{Range{{1, scalar_units}, {1, scalar_units + 1}}, "!"}, + }; + const auto rebuilt = store.apply_changes(uri, 4, rebuilding); + require(rebuilt.has_value()); + expect_eq((*rebuilt)->text, ascii + "\r\n" + astral + "!"); + expect((*rebuilt)->position_to_offset({1, scalar_units}) == line_bytes + 6); + expect(!(*rebuilt)->offset_to_position(line_bytes + 1)); + + const auto replaced = + store.apply_changes(uri, 5, std::array{TextEdit{std::nullopt, ascii}}); + require(replaced.has_value()); + expect((*replaced)->offset_to_position(line_bytes) == Position{0, line_bytes}); + expect(!(*replaced)->position_to_offset({1, 0})); + expect((*original)->position_to_offset({0, pivot + 1}) == pivot + 1); + expect(!(*mixed)->position_to_offset({0, pivot + 1})); + expect_eq((*mixed)->text, expected_mixed); + } +} diff --git a/tests/features/CompletionTests.cpp b/tests/features/CompletionTests.cpp new file mode 100644 index 0000000..fb7a470 --- /dev/null +++ b/tests/features/CompletionTests.cpp @@ -0,0 +1,143 @@ +#include + +#include +#include + +#include +#include + +namespace { +using namespace vls::features::completion; +using Void::Testing::expect; +using Void::Testing::require; + +Candidate make_candidate(std::string label, Kind kind = Kind::function, std::string detail = {}) { + return {std::move(label), kind, std::move(detail), "gcc"}; +} + +std::vector labels(const Result &result) { + std::vector names; + for (const auto &item : result.items) + names.push_back(item.label); + return names; +} +} // namespace + +VOID_TEST(Completion, prefix_is_the_identifier_before_the_offset) { + expect(prefix_at("value.", 6).empty()); + expect(prefix_at("value.fo", 8) == "fo"); + expect(prefix_at("fo", 2) == "fo"); + expect(prefix_at(" foo_bar", 9) == "foo_bar"); + expect(prefix_at("_x", 2) == "_x"); + expect(prefix_at("1abc", 4).empty()); + expect(prefix_at("abc", 1) == "a"); + expect(prefix_at("abc", 4).empty()); +} + +VOID_TEST(Completion, filters_by_prefix_and_replaces_it) { + const std::vector candidates{make_candidate("value"), make_candidate("validate"), + make_candidate("other")}; + const auto result = complete(candidates, "int va = 0;", 6); + expect(labels(result) == std::vector{"validate", "value"}); + for (const auto &item : result.items) { + expect(item.replacement_start == 4); + expect(item.replacement_end == 6); + } + expect(result.incomplete); + expect(result.backend == "symbol-index"); +} + +VOID_TEST(Completion, deduplicates_by_label_and_kind) { + const std::vector candidates{make_candidate("f", Kind::function), + make_candidate("f", Kind::function), + make_candidate("f", Kind::variable)}; + const auto result = complete(candidates, "f", 1); + require(result.items.size() == 2); + expect(result.items[0].kind == Kind::function); + expect(result.items[1].kind == Kind::variable); +} + +VOID_TEST(Completion, ranks_types_before_functions_before_variables) { + const std::vector candidates{make_candidate("zz", Kind::variable), + make_candidate("zz", Kind::function), + make_candidate("zz", Kind::type)}; + const auto result = complete(candidates, "z", 1); + require(result.items.size() == 3); + expect(result.items[0].kind == Kind::type); + expect(result.items[1].kind == Kind::function); + expect(result.items[2].kind == Kind::variable); + expect(result.items[0].sort_text == "0zz"); +} + +VOID_TEST(Completion, empty_prefix_lists_everything_bounded) { + const std::vector candidates{make_candidate("b"), make_candidate("a")}; + const auto result = complete(candidates, "", 0, Limits{.candidates = 1}); + require(result.items.size() == 1); + expect(result.items.front().label == "a"); + const auto unrestricted = complete(candidates, "", 0); + expect(labels(unrestricted) == std::vector{"a", "b"}); +} + +VOID_TEST(Completion, bounds_every_field_and_rejects_oversized_labels) { + const std::vector candidates{ + make_candidate("x", Kind::function, std::string(600, 'd')), + make_candidate(std::string(300, 'y'), Kind::function)}; + const auto result = complete(candidates, "x", 1); + require(result.items.size() == 1); + expect(result.items.front().detail.size() == 512); + expect(result.items.front().provenance.size() <= 128); +} + +namespace { +Identity identity(std::string name = "f", std::string path = "/project/a.cpp", + std::uint32_t line = 3) { + return {std::move(name), std::move(path), line, 4}; +} + +Detail detail(std::string text = "int f()", std::string provenance = "gcc") { + return {identity(), Kind::function, std::move(text), std::move(provenance)}; +} +} // namespace + +VOID_TEST(Completion, resolve_returns_details_for_the_same_generation) { + const std::vector current{detail()}; + const auto resolved = resolve(identity(), 7, 7, current); + expect(resolved.status == Resolved::Status::resolved); + expect(resolved.detail == "int f()"); + expect(resolved.documentation.find("int f()") != std::string::npos); + expect(resolved.documentation.find("/project/a.cpp:3:4") != std::string::npos); + expect(resolved.documentation.find("Provenance: gcc") != std::string::npos); +} + +VOID_TEST(Completion, resolve_is_stale_after_a_generation_change) { + const std::vector current{detail()}; + const auto resolved = resolve(identity(), 7, 8, current); + expect(resolved.status == Resolved::Status::stale); + expect(resolved.documentation.empty() && resolved.detail.empty()); +} + +VOID_TEST(Completion, resolve_is_unknown_for_a_missing_or_different_identity) { + const std::vector current{detail()}; + const auto missing = resolve(identity("absent"), 7, 7, current); + expect(missing.status == Resolved::Status::unknown); + const auto other_path = resolve(identity("f", "/project/b.cpp"), 7, 7, current); + expect(other_path.status == Resolved::Status::unknown); + const auto other_line = resolve(identity("f", "/project/a.cpp", 9), 7, 7, current); + expect(other_line.status == Resolved::Status::unknown); +} + +VOID_TEST(Completion, resolve_fences_hostile_content) { + const std::vector current{detail("text with ``` a fence and even ```` four")}; + const auto resolved = resolve(identity(), 7, 7, current); + require(resolved.status == Resolved::Status::resolved); + expect(resolved.documentation.starts_with("`````text")); + expect(resolved.documentation.find("\n`````\n") != std::string::npos); +} + +VOID_TEST(Completion, resolve_bounds_the_documentation_and_keeps_the_fence_closed) { + const std::vector current{detail(std::string(4000, 'x'))}; + const auto resolved = resolve(identity(), 7, 7, current, Limits{.detailBytes = 128}); + require(resolved.status == Resolved::Status::resolved); + expect(resolved.documentation.size() <= 128); + expect(resolved.documentation.ends_with("\n```\n")); +} diff --git a/tests/features/IndexNavigationTests.cpp b/tests/features/IndexNavigationTests.cpp new file mode 100644 index 0000000..2bfb675 --- /dev/null +++ b/tests/features/IndexNavigationTests.cpp @@ -0,0 +1,157 @@ +#include + +#include +#include + +#include +#include +#include + +namespace { +using namespace vls; +using Void::Testing::expect; +using Void::Testing::require; + +index::SymbolRecord record(std::string name, std::string path, std::uint32_t line, + std::optional definition = std::nullopt) { + return {std::move(name), + index::SymbolKind::function, + index::Location{std::move(path), line, 4, line, 8}, + std::move(definition), + {}, + "gcc"}; +} + +index::ContextInput context(std::string name, std::vector records, + bool complete = true) { + index::ContextInput input; + input.context = std::move(name); + input.records = std::move(records); + input.complete = complete; + if (!complete) + input.reason = "the observer could not complete this context"; + input.sources = {{"/project/a.cpp", "content-a"}, {"/project/b.cpp", "content-b"}}; + input.dependencies = {"/project/a.cpp", "/project/b.cpp"}; + return input; +} + +std::vector sources(bool editable = true) { + return {{"/project/a.cpp", "content-a", editable}, {"/project/b.cpp", "content-b", editable}}; +} + +navigation::Position at(std::uint32_t line, std::uint32_t character) { return {line, character}; } +} // namespace + +VOID_TEST(IndexNavigation, cross_file_rename_is_ready_from_index_data) { + index::SymbolIndex symbols; + const index::Location definition{"/project/def.cpp", 10, 0, 10, 1}; + require(symbols.publish(context("debug:a", {record("f", "/project/a.cpp", 3, definition)}))); + require(symbols.publish(context("debug:b", {record("f", "/project/b.cpp", 7, definition)}))); + const auto generation = symbols.current(); + require(generation != nullptr); + navigation::FactSet set; + require(features::ingest_index_facts(set, *generation, sources()) == 2); + const auto binding = navigation::binding_at(set, "/project/a.cpp", at(3, 5)); + require(binding.has_value()); + expect(binding->name == "f"); + require(binding->definition.has_value()); + expect(binding->definition->path == "/project/def.cpp"); + const auto refused = navigation::prepare_rename(set, "/project/a.cpp", at(3, 5), "g", false); + expect(refused.refusal == navigation::Refusal::multi_file_without_transaction); + const auto plan = navigation::prepare_rename(set, "/project/a.cpp", at(3, 5), "g", true); + require(plan.ready()); + require(plan.edits.size() == 2); + expect(plan.edits[0].path == "/project/a.cpp"); + expect(plan.edits[1].path == "/project/b.cpp"); + expect(plan.edits[1].range.start.line == 7); +} + +VOID_TEST(IndexNavigation, existing_facts_win_over_index_duplicates) { + index::SymbolIndex symbols; + require(symbols.publish(context("debug:a", {record("f", "/project/a.cpp", 3)}))); + const auto generation = symbols.current(); + require(generation != nullptr); + navigation::FactSet set; + set.facts.push_back(navigation::Fact{.binding = {.name = "f", .definition = std::nullopt}, + .context = "debug:a", + .source = "/project/a.cpp", + .content = "content-a", + .use = {{3, 4}, {3, 8}}, + .editable = true, + .provenance = "stock-observer"}); + expect(features::ingest_index_facts(set, *generation, sources()) == 0); + require(set.facts.size() == 1); + expect(set.facts.front().provenance == "stock-observer"); +} + +VOID_TEST(IndexNavigation, unknown_or_non_editable_sources_block_rename) { + index::SymbolIndex symbols; + require(symbols.publish(context("debug:a", {record("f", "/project/a.cpp", 3)}))); + const auto generation = symbols.current(); + require(generation != nullptr); + navigation::FactSet set; + require(features::ingest_index_facts(set, *generation, {}) == 1); + expect(!set.facts.front().editable); + const auto unknown = navigation::prepare_rename(set, "/project/a.cpp", at(3, 5), "g", true); + expect(unknown.refusal == navigation::Refusal::non_editable_origin); + + navigation::FactSet read_only; + require(features::ingest_index_facts(read_only, *generation, sources(false)) == 1); + const auto refused = + navigation::prepare_rename(read_only, "/project/a.cpp", at(3, 5), "g", true); + expect(refused.refusal == navigation::Refusal::non_editable_origin); +} + +VOID_TEST(IndexNavigation, stale_index_content_is_detected) { + index::SymbolIndex symbols; + require(symbols.publish(context("debug:a", {record("f", "/project/a.cpp", 3)}))); + const auto generation = symbols.current(); + require(generation != nullptr); + navigation::FactSet set; + require(features::ingest_index_facts(set, *generation, sources()) == 1); + set.current_sources["/project/a.cpp"] = "content-changed"; + const auto stale = navigation::prepare_rename(set, "/project/a.cpp", at(3, 5), "g", true); + expect(stale.refusal == navigation::Refusal::stale_source); +} + +VOID_TEST(IndexNavigation, incomplete_context_blocks_rename) { + index::SymbolIndex symbols; + require(symbols.publish(context("debug:a", {record("f", "/project/a.cpp", 3)}, false))); + const auto generation = symbols.current(); + require(generation != nullptr); + navigation::FactSet set; + require(features::ingest_index_facts(set, *generation, sources()) == 1); + const auto plan = navigation::prepare_rename(set, "/project/a.cpp", at(3, 5), "g", true); + expect(plan.refusal == navigation::Refusal::incomplete_coverage); + expect(plan.detail.find("debug:a") != std::string::npos); +} + +VOID_TEST(IndexNavigation, known_contexts_keep_their_own_completeness) { + index::SymbolIndex symbols; + require(symbols.publish(context("debug:a", {record("f", "/project/a.cpp", 3)}))); + const auto generation = symbols.current(); + require(generation != nullptr); + navigation::FactSet set; + set.contexts.push_back({"debug:a", false, "occurrence coverage was partial"}); + require(features::ingest_index_facts(set, *generation, sources()) == 1); + require(set.contexts.size() == 1); + expect(!set.contexts.front().complete); + expect(set.contexts.front().reason == "occurrence coverage was partial"); +} + +VOID_TEST(IndexNavigation, references_join_across_files) { + index::SymbolIndex symbols; + const index::Location definition{"/project/def.cpp", 10, 0, 10, 1}; + auto first = record("f", "/project/a.cpp", 3, definition); + first.references.push_back(index::Location{"/project/b.cpp", 7, 4, 7, 8}); + require(symbols.publish(context("debug:a", {first}))); + const auto generation = symbols.current(); + require(generation != nullptr); + navigation::FactSet set; + require(features::ingest_index_facts(set, *generation, sources()) == 2); + const auto binding = navigation::binding_at(set, "/project/a.cpp", at(3, 5)); + require(binding.has_value()); + const auto result = navigation::references(set, *binding); + expect(result.coverage_complete); + require(result.locations.size() == 2); +} diff --git a/tests/features/SignatureHelpTests.cpp b/tests/features/SignatureHelpTests.cpp new file mode 100644 index 0000000..992b249 --- /dev/null +++ b/tests/features/SignatureHelpTests.cpp @@ -0,0 +1,159 @@ +#include + +#include +#include + +#include +#include + +namespace { +using namespace vls::features::signature; +using Void::Testing::expect; +using Void::Testing::require; + +std::vector parameter_labels(const Signature &signature) { + std::vector labels; + for (const auto ¶meter : signature.parameters) + labels.push_back(parameter.label); + return labels; +} + +std::vector single(std::string_view text) { return {std::string{text}}; } +} // namespace + +VOID_TEST(SignatureHelp, parses_a_plain_signature) { + const auto parsed = parse("std::string_view Void::Hash::fnv1a64(std::string_view)"); + expect(parsed.label == "std::string_view Void::Hash::fnv1a64(std::string_view)"); + expect(parameter_labels(parsed) == std::vector{"std::string_view"}); + require(parsed.parameters.front().range.has_value()); + expect(parsed.parameters.front().range->second - parsed.parameters.front().range->first == + parsed.parameters.front().label.size()); + expect(parsed.label.substr(parsed.parameters.front().range->first, + parsed.parameters.front().label.size()) == + parsed.parameters.front().label); +} + +VOID_TEST(SignatureHelp, splits_multiple_parameters) { + const auto parsed = parse("int twice(int, double, const char *)"); + expect(parameter_labels(parsed) == std::vector{"int", "double", "const char *"}); + for (const auto ¶meter : parsed.parameters) { + require(parameter.range.has_value()); + expect(parsed.label.substr(parameter.range->first, parameter.label.size()) == + parameter.label); + } +} + +VOID_TEST(SignatureHelp, ignores_commas_in_nested_brackets_and_templates) { + const auto parsed = + parse("void f(std::pair, std::array, int (*)(int, int), int[])"); + expect(parameter_labels(parsed) == std::vector{"std::pair", + "std::array", + "int (*)(int, int)", "int[]"}); +} + +VOID_TEST(SignatureHelp, handles_empty_and_missing_parameter_lists) { + expect(parse("int f()").parameters.empty()); + expect(parse("int f( )").parameters.empty()); + expect(parse("int value").parameters.empty()); + expect(parse("broken(").parameters.empty()); + expect(parse("").label.empty()); + expect(parse("int f(int,)").parameters.size() == 1); +} + +VOID_TEST(SignatureHelp, counts_top_level_commas) { + const std::string call = "f(a, b, c);"; + expect(active_parameter(call, call.find("(a") + 2) == 0); + expect(active_parameter(call, call.find("b")) == 1); + expect(active_parameter(call, call.find("c")) == 2); + expect(active_parameter(call, call.find(");")) == 2); +} + +VOID_TEST(SignatureHelp, nested_calls_and_brackets_do_not_count) { + const std::string call = "outer(inner(1, 2), [3, 4], {5, 6}, "; + expect(active_parameter(call, call.size()) == 3); + const std::string nested = "outer(inner(1, 2))"; + // Inside inner's second argument, not the outer call. + expect(active_parameter(nested, nested.find("2)")) == 1); +} + +VOID_TEST(SignatureHelp, literals_and_comments_do_not_count) { + const std::string call = R"(f("a, b", 'x', /* , */ suffix, // , + after))"; + expect(active_parameter(call, call.find("suffix")) == 2); + expect(active_parameter(call, call.size() - 2) == 3); + expect(active_parameter(R"(f("unterminated, )", 20) == 0); +} + +VOID_TEST(SignatureHelp, without_an_open_parenthesis_the_parameter_is_zero) { + expect(active_parameter("int value = f", 14) == 0); + expect(active_parameter("", 0) == 0); + expect(active_parameter("f(a", 99) == 0); +} + +VOID_TEST(SignatureHelp, backward_scan_is_bounded) { + Limits limits; + limits.scanBytes = 3; + const std::string call = std::string(64, ' ') + "f(a, b"; + expect(active_parameter(call, call.size(), limits) == 0); + expect(active_parameter(call, call.size()) == 1); +} + +VOID_TEST(SignatureHelp, build_assembles_signatures_and_active_parameter) { + const std::vector signatures{"int f(int, int)", ""}; + const std::string call = "auto x = f(1, "; + const auto result = build(signatures, call, call.size()); + require(result.signatures.size() == 1); + expect(result.active_signature == 0); + expect(result.active_parameter == 1); + const std::vector none; + expect(build(none, call, call.size()).signatures.empty()); + const std::vector empty{"", ""}; + expect(build(empty, call, call.size()).signatures.empty()); +} + +VOID_TEST(SignatureHelp, build_bounds_signatures_and_parameters) { + Limits limits; + limits.signatures = 1; + limits.parameters = 2; + limits.labelBytes = 16; + const std::vector signatures{"int f(int, int, int)", "int g(int)"}; + const auto result = build(signatures, "f(1, 2, 3)", 9, limits); + require(result.signatures.size() == 1); + expect(result.signatures.front().label.size() == 16); + expect(result.signatures.front().parameters.size() == 2); + expect(result.active_parameter == 2); + limits.parameterBytes = 3; + const auto short_parameters = parse("int f(long long)", limits); + require(!short_parameters.parameters.empty()); + expect(short_parameters.parameters.front().label.size() == 3); +} + +VOID_TEST(SignatureHelp, in_call_spans_the_argument_list) { + const std::string_view call = "add(1, 2)"; + expect(!in_call(call, 0, 3, 3)); + expect(in_call(call, 0, 3, 4)); + expect(in_call(call, 0, 3, 6)); + expect(in_call(call, 0, 3, 8)); + expect(!in_call(call, 0, 3, 9)); + expect(!in_call(call, 4, 2, 6)); + expect(!in_call("add 1", 0, 3, 3)); +} + +VOID_TEST(SignatureHelp, in_call_ignores_literals_and_comments) { + const std::string text = R"x(f(a, ")", /* ) */ b))x"; + const auto inside = text.find("b)"); + expect(in_call(text, 0, 1, inside)); + const std::string closed = R"y(f(")"))y"; + expect(!in_call(closed, 0, 1, closed.size())); +} + +VOID_TEST(SignatureHelp, in_call_scan_is_bounded) { + Limits limits; + limits.scanBytes = 4; + const std::string call = "f(" + std::string(32, 'x') + ", y)"; + expect(in_call(call, 0, 1, call.size() - 1, limits)); + const std::string long_call = "f(" + std::string(32, 'x') + ")"; + // The matching ')' lies outside the bounded window, so the answer stays + // conservative (still inside) rather than inventing a close. + expect(in_call(long_call, 0, 1, long_call.size() - 1, limits)); +} diff --git a/tests/index/SymbolIndexTests.cpp b/tests/index/SymbolIndexTests.cpp new file mode 100644 index 0000000..0290640 --- /dev/null +++ b/tests/index/SymbolIndexTests.cpp @@ -0,0 +1,443 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +using namespace vls::index; +using Void::Testing::expect; +using Void::Testing::require; + +SymbolRecord record(std::string name, std::string path, std::uint32_t line, + SymbolKind kind = SymbolKind::function) { + return {std::move(name), kind, Location{std::move(path), line, 0, line, 4}, + std::nullopt, {}, "gcc"}; +} + +ContextInput context(std::string name, std::vector records, bool complete = true, + std::string source = "/project/unit.cpp") { + ContextInput input; + input.context = std::move(name); + input.records = std::move(records); + input.complete = complete; + input.sources = {{source, "content-1"}}; + input.dependencies = {source}; + return input; +} + +std::size_t count(const Result &result) { return result.symbols.size(); } +} // namespace + +VOID_TEST(SymbolIndex, publishes_and_queries) { + SymbolIndex index; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + expect(index.records() == 1 && index.generation() == 1); + const auto result = index.find({.name = "f"}); + require(count(result) == 1); + expect(result.symbols.front().name == "f"); + expect(result.coverage.indexed && result.coverage.complete && !result.truncated); + expect(count(index.find({.name = "missing"})) == 0); +} + +VOID_TEST(SymbolIndex, contexts_distinguish_same_spelling) { + SymbolIndex index; + require(index.publish(context("debug:a", {record("f", "/project/a.cpp", 1)}))); + require(index.publish(context("debug:b", {record("f", "/project/b.cpp", 9)}))); + expect(count(index.find({.name = "f"})) == 2); + const auto filtered = index.find({.name = "f", .context = "debug:b"}); + require(count(filtered) == 1); + expect(filtered.symbols.front().location.path == "/project/b.cpp"); +} + +VOID_TEST(SymbolIndex, overlay_shadows_and_reconciles) { + SymbolIndex index; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + require( + index.set_overlay("/project/unit.cpp", "content-2", {record("g", "/project/unit.cpp", 7)})); + expect(count(index.find({.name = "f"})) == 0); + expect(count(index.find({.name = "g"})) == 1); + require(index.clear_overlay("/project/unit.cpp")); + expect(count(index.find({.name = "f"})) == 1); + expect(count(index.find({.name = "g"})) == 0); +} + +VOID_TEST(SymbolIndex, changed_source_marks_incomplete_without_dropping_records) { + SymbolIndex index; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + expect(index.invalidate("/project/unit.cpp", std::string{"content-2"}) == 1); + const auto coverage = index.coverage(); + expect(coverage.indexed && !coverage.complete && + coverage.incomplete == std::vector{"debug:unit"}); + expect(count(index.find({.name = "f"})) == 1); + expect(index.invalidate("/project/unit.cpp", std::string{"content-2"}) == 0); +} + +VOID_TEST(SymbolIndex, dependency_invalidation_without_owned_records) { + SymbolIndex index; + auto input = context("debug:unit", {record("f", "/project/unit.cpp", 3)}); + input.dependencies.push_back("/project/header.hpp"); + require(index.publish(input)); + expect(index.invalidate("/project/header.hpp", std::nullopt) == 1); + expect(!index.coverage().complete); +} + +VOID_TEST(SymbolIndex, removed_context_drops_records) { + SymbolIndex index; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + require(index.remove("debug:unit")); + expect(count(index.find({.name = "f"})) == 0); + expect(!index.coverage().indexed); + expect(!index.remove("debug:unit")); +} + +VOID_TEST(SymbolIndex, generations_retain_readers) { + SymbolIndex index; + require(index.publish(context("debug:a", {record("a", "/project/a.cpp", 1)}))); + const auto first = index.current(); + require(first != nullptr); + expect(first->number() == 1 && first->symbols().size() == 1); + require(index.publish(context("debug:b", {record("b", "/project/b.cpp", 2)}))); + expect(index.current()->number() == 2); + expect(first->number() == 1 && first->symbols().size() == 1); +} + +VOID_TEST(SymbolIndex, persists_and_reloads) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto path = temp.path() / "index.json"; + SymbolIndex index; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + require( + index.set_overlay("/project/unit.cpp", "content-2", {record("g", "/project/unit.cpp", 7)})); + require(index.save(path)); + SymbolIndex loaded; + require(loaded.load(path)); + expect(count(loaded.find({.name = "f"})) == 0); + expect(count(loaded.find({.name = "g"})) == 1); + expect(loaded.generation() == 2); +} + +VOID_TEST(SymbolIndex, rejects_incompatible_or_corrupt_snapshots) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + SymbolIndex index; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + const auto path = temp.path() / "index.json"; + require(index.save(path)); + auto bytes = [&] { + std::ifstream stream{path, std::ios::binary}; + return std::string{std::istreambuf_iterator{stream}, {}}; + }(); + auto incompatible = bytes; + const auto schema = incompatible.find("\"schema\":2"); + require(schema != std::string::npos); + incompatible.replace(schema, 10, "\"schema\":9"); + { + std::ofstream stream{path, std::ios::binary | std::ios::trunc}; + stream << incompatible; + } + expect(!index.load(path)); + { + std::ofstream stream{path, std::ios::binary | std::ios::trunc}; + stream << "not json"; + } + expect(!index.load(path)); + expect(count(index.find({.name = "f"})) == 1); +} + +VOID_TEST(SymbolIndex, rejects_oversized_snapshots) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + Limits limits; + limits.snapshotBytes = 128; + SymbolIndex index{limits}; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + const auto path = temp.path() / "index.json"; + expect(!index.save(path)); + expect(!fs::exists(path)); +} + +VOID_TEST(SymbolIndex, limit_truncates_deterministically) { + SymbolIndex index; + std::vector records; + for (int value = 0; value != 5; ++value) + records.push_back(record("f" + std::to_string(value), "/project/unit.cpp", + static_cast(value))); + require(index.publish(context("debug:unit", records))); + const auto result = index.find({.name = "f", .substring = true, .limit = 2}); + expect(result.truncated && count(result) == 2); + expect(result.symbols.front().name == "f0" && result.symbols.back().name == "f1"); +} + +VOID_TEST(SymbolIndex, rejects_invalid_input) { + SymbolIndex index; + expect(!index.publish(context("debug:unit", {record("", "/project/unit.cpp", 1)}))); + expect(!index.publish(context("debug:unit", {record("f", "", 1)}))); + Limits limits; + limits.contexts = 1; + SymbolIndex bounded{limits}; + require(bounded.publish(context("debug:a", {record("a", "/project/a.cpp", 1)}))); + expect(!bounded.publish(context("debug:b", {record("b", "/project/b.cpp", 2)}))); + expect(!bounded.set_overlay("", "content", {})); +} + +VOID_TEST(SymbolIndex, restore_reports_missing_and_loaded) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto path = temp.path() / "index.json"; + SymbolIndex index; + const auto missing = index.restore(path); + require(missing.has_value()); + expect(missing->status == SymbolIndex::LoadStatus::missing); + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + require(index.save(path)); + const auto loaded = index.restore(path); + require(loaded.has_value()); + expect(loaded->status == SymbolIndex::LoadStatus::loaded && !loaded->quarantine.has_value()); + expect(count(index.find({.name = "f"})) == 1); +} + +VOID_TEST(SymbolIndex, quarantines_incompatible_snapshots_and_rebuilds) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto path = temp.path() / "index.json"; + SymbolIndex index; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + require(index.save(path)); + auto bytes = [&] { + std::ifstream stream{path, std::ios::binary}; + return std::string{std::istreambuf_iterator{stream}, {}}; + }(); + const auto schema = bytes.find("\"schema\":2"); + require(schema != std::string::npos); + bytes.replace(schema, 10, "\"schema\":9"); + { + std::ofstream stream{path, std::ios::binary | std::ios::trunc}; + stream << bytes; + } + const auto generation = index.generation(); + const auto restored = index.restore(path); + require(restored.has_value()); + expect(restored->status == SymbolIndex::LoadStatus::incompatible); + require(restored->quarantine.has_value()); + expect(fs::is_regular_file(*restored->quarantine)); + expect(!fs::exists(path)); + expect(restored->generation > generation); + expect(index.records() == 0 && !index.coverage().indexed); +} + +VOID_TEST(SymbolIndex, quarantines_corrupt_snapshots) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto path = temp.path() / "index.json"; + { + std::ofstream stream{path, std::ios::binary | std::ios::trunc}; + stream << "not json"; + } + SymbolIndex index; + const auto restored = index.restore(path); + require(restored.has_value()); + expect(restored->status == SymbolIndex::LoadStatus::corrupt); + expect(restored->quarantine.has_value()); + expect(!fs::exists(path)); +} + +VOID_TEST(SymbolIndex, generation_backend_persists_and_recovers) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto root = temp.path() / "index"; + SymbolIndex index; + require(index.publish(context("debug:a", {record("a", "/project/a.cpp", 1)}))); + require(index.save_generation(root)); + require(index.publish(context("debug:b", {record("b", "/project/b.cpp", 2)}))); + require(index.save_generation(root)); + SymbolIndex loaded; + const auto latest = loaded.restore_generation(root); + require(latest.has_value()); + expect(latest->status == SymbolIndex::LoadStatus::loaded); + expect(count(loaded.find({.name = "b"})) == 1); + { + std::ofstream stream{root / "snapshot.json", std::ios::binary | std::ios::trunc}; + stream << "corrupt"; + } + SymbolIndex recovered; + const auto restored = recovered.restore_generation(root); + require(restored.has_value()); + expect(restored->status == SymbolIndex::LoadStatus::loaded); + expect(count(recovered.find({.name = "a"})) == 1); +} + +VOID_TEST(SymbolIndex, generation_backend_migrates_a_legacy_snapshot) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto root = temp.path() / "index"; + fs::create_directories(root); + SymbolIndex index; + require(index.publish(context("debug:a", {record("a", "/project/a.cpp", 1)}))); + require(index.save(root / "index.json")); + SymbolIndex loaded; + const auto restored = loaded.restore_generation(root); + require(restored.has_value()); + expect(restored->status == SymbolIndex::LoadStatus::loaded); + expect(fs::exists(root / "CURRENT") && fs::exists(root / "snapshot.json")); +} + +VOID_TEST(SymbolIndex, generation_backend_reports_missing) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + SymbolIndex index; + const auto restored = index.restore_generation(temp.path() / "absent"); + require(restored.has_value()); + expect(restored->status == SymbolIndex::LoadStatus::missing); +} + +VOID_TEST(SymbolIndex, generation_selector_migrates_from_the_legacy_format) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto root = temp.path() / "index"; + SymbolIndex index; + require(index.publish(context("debug:a", {record("a", "/project/a.cpp", 1)}))); + require(index.save_generation(root)); + { + std::ofstream stream{root / "CURRENT", std::ios::binary | std::ios::trunc}; + stream << "snapshot.json\n"; + } + SymbolIndex loaded; + const auto restored = loaded.restore_generation(root); + require(restored.has_value()); + expect(restored->status == SymbolIndex::LoadStatus::loaded); + std::ifstream selector{root / "CURRENT", std::ios::binary}; + const std::string text{std::istreambuf_iterator{selector}, {}}; + expect(text.find("\"schema\":2") != std::string::npos); + { + std::ofstream stream{root / "CURRENT", std::ios::binary | std::ios::trunc}; + stream << "future.json\n"; + } + SymbolIndex rejected; + expect(!rejected.restore_generation(root).has_value()); +} + +VOID_TEST(SymbolIndex, generation_backend_recovers_a_missing_current_file) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto root = temp.path() / "index"; + SymbolIndex index; + require(index.publish(context("debug:a", {record("a", "/project/a.cpp", 1)}))); + require(index.save_generation(root)); + require(index.publish(context("debug:b", {record("b", "/project/b.cpp", 2)}))); + require(index.save_generation(root)); + fs::remove(root / "snapshot.json"); + SymbolIndex recovered; + const auto restored = recovered.restore_generation(root); + require(restored.has_value()); + expect(restored->status == SymbolIndex::LoadStatus::loaded); + expect(count(recovered.find({.name = "a"})) == 1); + expect(fs::is_regular_file(root / "snapshot.json")); +} + +namespace { +std::string file_text(const fs::path &path) { + std::ifstream stream{path, std::ios::binary}; + require(stream.good()); + return {std::istreambuf_iterator{stream}, std::istreambuf_iterator{}}; +} + +void put_text(const fs::path &path, std::string_view text) { + std::ofstream stream{path, std::ios::binary | std::ios::trunc}; + stream.write(text.data(), static_cast(text.size())); +} + +// Rewrites a schema-2 snapshot as the earlier schema-1 format: no digest. +std::string downgrade(std::string bytes) { + const auto digest = bytes.find(",\"digest\":\""); + require(digest != std::string::npos); + const auto end = bytes.find('"', digest + 12); + require(end != std::string::npos); + bytes.erase(digest, end + 1 - digest); + const auto schema = bytes.find("\"schema\":2"); + require(schema != std::string::npos); + bytes.replace(schema, 10, "\"schema\":1"); + return bytes; +} +} // namespace + +VOID_TEST(SymbolIndex, snapshot_schema_migration_is_reported_and_rewritten) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto path = temp.path() / "index.json"; + SymbolIndex index; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + require(index.save(path)); + put_text(path, downgrade(file_text(path))); + SymbolIndex loaded; + const auto restored = loaded.restore(path); + require(restored.has_value()); + expect(restored->status == SymbolIndex::LoadStatus::loaded); + expect(restored->migrated); + expect(count(loaded.find({.name = "f"})) == 1); + const auto upgraded = temp.path() / "upgraded.json"; + require(loaded.save(upgraded)); + const auto bytes = file_text(upgraded); + expect(bytes.find("\"schema\":2") != std::string::npos); + expect(bytes.find("\"digest\":\"") != std::string::npos); + SymbolIndex reread; + expect(reread.load(upgraded)); + expect(count(reread.find({.name = "f"})) == 1); +} + +VOID_TEST(SymbolIndex, generation_restore_persists_the_migrated_schema) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto root = temp.path() / "index"; + SymbolIndex index; + require(index.publish(context("debug:a", {record("a", "/project/a.cpp", 1)}))); + require(index.save_generation(root)); + put_text(root / "snapshot.json", downgrade(file_text(root / "snapshot.json"))); + SymbolIndex loaded; + const auto restored = loaded.restore_generation(root); + require(restored.has_value()); + expect(restored->status == SymbolIndex::LoadStatus::loaded); + expect(restored->migrated); + expect(count(loaded.find({.name = "a"})) == 1); + const auto bytes = file_text(root / "snapshot.json"); + expect(bytes.find("\"schema\":2") != std::string::npos); + expect(bytes.find("\"digest\":\"") != std::string::npos); + expect(fs::is_regular_file(root / "snapshot.prev.json")); + SymbolIndex reread; + const auto again = reread.restore_generation(root); + require(again.has_value()); + expect(again->status == SymbolIndex::LoadStatus::loaded); + expect(!again->migrated); +} + +VOID_TEST(SymbolIndex, digest_mismatch_is_quarantined_as_corruption) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto path = temp.path() / "index.json"; + SymbolIndex index; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + require(index.save(path)); + auto bytes = file_text(path); + const auto digest = bytes.find("\"digest\":\""); + require(digest != std::string::npos); + const auto digit = digest + 10; + bytes[digit] = bytes[digit] == '0' ? '1' : '0'; + put_text(path, bytes); + const auto restored = index.restore(path); + require(restored.has_value()); + expect(restored->status == SymbolIndex::LoadStatus::corrupt); + expect(restored->quarantine.has_value()); + expect(!fs::exists(path)); +} + +VOID_TEST(SymbolIndex, schema_2_rejects_edited_records) { + Void::FileSystem::TempDir temp{"vls_symbol_index_"}; + const auto path = temp.path() / "index.json"; + SymbolIndex index; + require(index.publish(context("debug:unit", {record("f", "/project/unit.cpp", 3)}))); + require(index.save(path)); + auto bytes = file_text(path); + const auto name = bytes.find("\"name\":\"f\""); + require(name != std::string::npos); + bytes.replace(name, 11, "\"name\":\"\""); + put_text(path, bytes); + const auto restored = index.restore(path); + require(restored.has_value()); + // The digest still matches (the edit is a consistent rewrite only by hand), + // so either the digest or the record validation rejects it as corrupt. + expect(restored->status == SymbolIndex::LoadStatus::corrupt); + expect(restored->quarantine.has_value()); +} diff --git a/tests/modules/ArtifactCacheTests.cpp b/tests/modules/ArtifactCacheTests.cpp new file mode 100644 index 0000000..f2317b0 --- /dev/null +++ b/tests/modules/ArtifactCacheTests.cpp @@ -0,0 +1,307 @@ +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +using namespace vls::modules; +namespace Sched = vls::scheduler; +using Void::Testing::expect; +using Void::Testing::require; + +ArtifactKey key(std::string context, std::string inputs = "inputs") { + return {"gcc-16.2.0/x86_64", std::move(context), std::move(inputs), "cmi"}; +} + +fs::path write(const fs::path &root, std::string_view name, std::string_view text) { + const auto path = root / name; + fs::create_directories(path.parent_path()); + std::ofstream stream{path, std::ios::binary}; + stream << text; + stream.close(); + require(stream.good()); + return path; +} + +std::string read(const fs::path &path) { + std::ifstream stream{path, std::ios::binary}; + require(stream.good()); + return {std::istreambuf_iterator{stream}, {}}; +} + +std::size_t files(const fs::path &root) { + std::size_t count{}; + for (const auto &entry : fs::directory_iterator{root}) + if (entry.is_regular_file()) + ++count; + return count; +} + +ModulePlan ready_plan(std::vector &keys) { + ModulePlan plan; + plan.domain.compatibility = "gcc-16.2.0/x86_64"; + plan.claims_complete = true; + for (std::size_t index = 0; index != 3; ++index) { + const auto name = "unit" + std::to_string(index); + Build::ContextKey context{ + {}, {}, Build::ContextRole::target, name, fs::path{"/project"} / (name + ".cpp")}; + CensusMember member{context, + {"/project", name + ".o"}, + {"command-" + name, "source-" + name, "closure-" + name, {}}, + "scan-" + name, + {}}; + plan.units.push_back({member, UnitKind::primary_interface, {}}); + plan.order.push_back(context); + keys.push_back(context); + } + return plan; +} +} // namespace + +VOID_TEST(ArtifactCache, publishes_and_finds) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache"}; + const auto first = write(temp.path() / "src", "first.gcm", "first artifact"); + const auto second = write(temp.path() / "src", "second.gcm", "second artifact"); + auto published = cache.publish({{key("one"), first}, {key("two"), second}}); + require(published.has_value()); + const auto generation = *published; + expect(generation->id().size() == 64); + expect(cache.current() == generation); + const auto one = generation->find(key("one")); + require(one.has_value()); + expect(read(one->path) == "first artifact" && one->sha256.size() == 64); + require(generation->find(key("two")).has_value()); + expect(!generation->find(key("missing")).has_value()); + expect(cache.generations() == 1); +} + +VOID_TEST(ArtifactCache, failed_publication_leaves_nothing) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache"}; + const auto valid = write(temp.path(), "valid.gcm", "valid"); + auto published = + cache.publish({{key("valid"), valid}, {key("missing"), temp.path() / "missing.gcm"}}); + require(!published.has_value()); + expect(!cache.current()); + expect(cache.generations() == 0); + expect(fs::is_empty(temp.path() / "cache" / "tmp")); +} + +VOID_TEST(ArtifactCache, identical_contents_share_one_file) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache"}; + const auto first = write(temp.path(), "first.gcm", "same bytes"); + const auto second = write(temp.path(), "second.gcm", "same bytes"); + auto published = cache.publish({{key("one"), first}, {key("two"), second}}); + require(published.has_value()); + expect(files((*published)->root()) == 2); // manifest plus one content file +} + +VOID_TEST(ArtifactCache, readers_retain_generations_across_collect) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache", 1}; + const auto source = write(temp.path(), "artifact.gcm", "retained"); + auto first = cache.publish({{key("one"), source}}); + require(first.has_value()); + const auto first_root = (*first)->root(); + require(cache.publish({{key("two"), source}}).has_value()); + require(cache.publish({{key("three"), source}}).has_value()); + cache.collect(); + expect(fs::is_directory(first_root)); + first = {}; + cache.collect(); + expect(!fs::exists(first_root)); + expect(cache.generations() == 2); +} + +VOID_TEST(ArtifactCache, eviction_respects_the_retained_limit) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache", 1}; + for (int index = 0; index != 5; ++index) { + const auto source = write(temp.path(), "artifact.gcm", "content " + std::to_string(index)); + require(cache.publish({{key("unit" + std::to_string(index)), source}}).has_value()); + } + expect(cache.generations() == 5); + cache.collect(); + expect(cache.generations() == 2); +} + +VOID_TEST(ArtifactCache, producer_publishes_in_dependency_order) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache"}; + std::vector keys; + const auto plan = ready_plan(keys); + std::vector order; + auto produced = produce_module_artifacts( + plan, cache, temp.path() / "staging", + [&](std::stop_token, const Build::ContextKey &context, + const fs::path &output) -> std::expected { + order.push_back(context.alternative); + fs::create_directories(output.parent_path()); + std::ofstream stream{output, std::ios::binary}; + stream << "artifact for " << context.alternative; + stream.close(); + if (!stream) + return std::unexpected(std::string{"write failed"}); + return output; + }); + require(produced.has_value()); + expect(order.size() == 3); + for (std::size_t index = 0; index != 3; ++index) + expect(order[index] == keys[index].alternative); + expect((*produced) + ->find(key(keys[0].alternative, "command-unit0|source-unit0|closure-unit0|")) + .has_value()); + expect(!fs::exists(temp.path() / "staging")); +} + +VOID_TEST(ArtifactCache, producer_failure_publishes_nothing) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache"}; + std::vector keys; + const auto plan = ready_plan(keys); + std::size_t calls{}; + auto produced = produce_module_artifacts( + plan, cache, temp.path() / "staging", + [&](std::stop_token, const Build::ContextKey &, + const fs::path &output) -> std::expected { + if (++calls == 2) + return std::unexpected("compile failed"); + fs::create_directories(output.parent_path()); + std::ofstream{output} << "artifact"; + return output; + }); + require(!produced.has_value()); + expect(produced.error() == "compile failed"); + expect(!cache.current()); + expect(cache.generations() == 0); + expect(!fs::exists(temp.path() / "staging")); +} + +VOID_TEST(ArtifactCache, producer_cancellation_publishes_nothing) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache"}; + std::vector keys; + const auto plan = ready_plan(keys); + std::stop_source cancellation; + cancellation.request_stop(); + auto produced = produce_module_artifacts( + plan, cache, temp.path() / "staging", + [](std::stop_token, const Build::ContextKey &, const fs::path &output) { + return std::expected{output}; + }, + cancellation.get_token()); + require(!produced.has_value()); + expect(cache.generations() == 0); +} + +VOID_TEST(ArtifactCache, refuses_an_unready_plan) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache"}; + ModulePlan plan; + plan.domain.compatibility = "gcc-16.2.0/x86_64"; + auto produced = produce_module_artifacts( + plan, cache, temp.path() / "staging", + [](std::stop_token, const Build::ContextKey &, const fs::path &output) { + return std::expected{output}; + }); + require(!produced.has_value()); + expect(produced.error() == "module plan is not ready"); +} + +VOID_TEST(ArtifactCache, scheduled_production_publishes_in_order) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache"}; + Sched::Scheduler pool{Sched::Budget{.foreground = 1, + .background = 1, + .artifact = 1, + .queued = 8, + .memory_mib = 64, + .watchdog = std::chrono::seconds{5}}}; + std::vector keys; + const auto plan = ready_plan(keys); + std::vector order; + auto produced = produce_module_artifacts_scheduled( + plan, cache, temp.path() / "staging", + [&](std::stop_token, const Build::ContextKey &context, + const fs::path &output) -> std::expected { + order.push_back(context.alternative); + fs::create_directories(output.parent_path()); + std::ofstream{output} << "artifact " << context.alternative; + return output; + }, + pool); + require(produced.has_value()); + expect(order.size() == 3); + for (std::size_t index = 0; index != 3; ++index) + expect(order[index] == keys[index].alternative); + expect((*produced) + ->find(key(keys[0].alternative, "command-unit0|source-unit0|closure-unit0|")) + .has_value()); +} + +VOID_TEST(ArtifactCache, superseded_scheduled_production_publishes_nothing) { + Void::FileSystem::TempDir temp{"vls_artifact_cache_"}; + ArtifactCache cache{temp.path() / "cache"}; + Sched::Scheduler pool{Sched::Budget{.foreground = 1, + .background = 1, + .artifact = 1, + .queued = 8, + .memory_mib = 64, + .watchdog = std::chrono::seconds{5}}}; + std::vector keys; + const auto plan = ready_plan(keys); + std::latch started{1}; + std::mutex mutex; + std::condition_variable changed; + bool release{}; + std::expected, std::string> result = + std::unexpected("not run"); + std::thread producer{[&] { + result = produce_module_artifacts_scheduled( + plan, cache, temp.path() / "staging", + [&](std::stop_token stop, const Build::ContextKey &, + const fs::path &output) -> std::expected { + started.count_down(); + std::unique_lock lock{mutex}; + changed.wait(lock, [&] { return release; }); + if (stop.stop_requested()) + return std::unexpected("cancelled"); + fs::create_directories(output.parent_path()); + std::ofstream{output} << "artifact"; + return output; + }, + pool); + }}; + started.wait(); + require(pool.submit( + {.priority = Sched::Priority::artifact, + .key = keys[0].alternative, + .revision = 2, + .memory_mib = 0}, + [](std::stop_token) { return std::string{}; }, [](Sched::Result) {})); + { + std::lock_guard lock{mutex}; + release = true; + changed.notify_all(); + } + producer.join(); + require(!result.has_value()); + expect(result.error() == "artifact production cancelled"); + expect(!cache.current()); + expect(cache.generations() == 0); +} diff --git a/tests/modules/GccScanFixture.cpp b/tests/modules/GccScanFixture.cpp new file mode 100644 index 0000000..3735f35 --- /dev/null +++ b/tests/modules/GccScanFixture.cpp @@ -0,0 +1,247 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace Modules = vls::modules; +namespace Build = Modules::Build; +namespace Protocol = Void::LanguageServer::Protocol; +namespace fs = std::filesystem; +using Json = Protocol::Json; + +constexpr std::size_t max_manifest_bytes = 2 * 1024 * 1024; +constexpr std::size_t max_report_bytes = 8192; + +const Json &field(const Json::Object &object, std::string_view name) { + if (const auto *value = Protocol::find_member(object, name)) + return *value; + throw std::runtime_error("missing field " + std::string(name)); +} + +const Json::Object &object(const Json &value) { + if (const auto *fields = Protocol::as_object(&value)) + return *fields; + throw std::runtime_error("expected an object"); +} + +const Json::Array &array(const Json &value, std::size_t limit) { + if (const auto *items = Protocol::as_array(&value); items && items->size() <= limit) + return *items; + throw std::runtime_error("expected a bounded array"); +} + +const std::string &string(const Json &value, std::size_t limit = Modules::max_field_bytes) { + if (const auto *text = Protocol::as_string(&value); text && text->size() <= limit) + return *text; + throw std::runtime_error("expected a bounded string"); +} + +const std::string &string(const Json::Object &value, std::string_view name) { + return string(field(value, name)); +} + +bool flag(const Json::Object &value, std::string_view name) { + if (const auto bit = Protocol::as_bool(&field(value, name))) + return *bit; + throw std::runtime_error("expected a boolean field " + std::string(name)); +} + +int exit_status(const Json::Object &value) { + if (const auto *code = std::get_if(&field(value, "exit").value); + code && *code >= 0 && *code <= 255) + return static_cast(*code); + throw std::runtime_error("expected an exit status"); +} + +Modules::ScanMethod scan_method(const std::vector &argv) { + const auto has = [&](std::string_view option) { return std::ranges::contains(argv, option); }; + if (has("-E") && has("-MD")) + return Modules::ScanMethod::preprocess_md; + if (has("-M") && has("-MG")) + return Modules::ScanMethod::missing_allowed; + throw std::runtime_error("unexpected fixture scan mode"); +} + +std::string_view kind_name(Modules::UnitKind kind) { + using enum Modules::UnitKind; + switch (kind) { + case unknown: + return "unknown"; + case ordinary: + return "ordinary"; + case implementation: + return "implementation"; + case primary_interface: + return "primary_interface"; + case interface_partition: + return "interface_partition"; + case internal_partition: + return "internal_partition"; + case header_unit: + return "header_unit"; + } + throw std::runtime_error("unexpected unit kind"); +} + +Json report(const Modules::ModulePlan &plan, const Modules::ModuleCensus &census) { + Json::Array order, blockers; + Json::Object units; + for (const auto &key : plan.order) + order.push_back(Json{key.alternative}); + for (const auto &unit : plan.units) { + Json::Array consumers; + for (const auto consumer : unit.consumers) + consumers.push_back(Json{plan.units.at(consumer).member.context.alternative}); + units.emplace(unit.member.context.alternative, + Json{Json::Object{{"kind", Json{std::string(kind_name(unit.kind))}}, + {"consumers", Json{std::move(consumers)}}}}); + } + for (const auto &blocker : plan.blockers) { + using enum Modules::PlanIssue; + const auto code = blocker.code; + std::string name = std::to_string(static_cast(code)); + if (code == scan_failed) + name = "scan_failed"; + else if (code == invalid_rule) + name = "invalid_rule"; + else if (code == incomplete_scan) + name = "incomplete_scan"; + else if (code == unproven_mapping) + name = "unproven_mapping"; + Json::Object status{{"code", Json{std::move(name)}}, {"detail", Json{blocker.detail}}}; + if (blocker.unit) + status.emplace("unit", Json{plan.units.at(*blocker.unit).member.context.alternative}); + if (blocker.scan_error == Modules::ScanError::invalid_json) + status.emplace("scan_error", Json{std::string("invalid_json")}); + else if (blocker.scan_error == Modules::ScanError::wrong_output) + status.emplace("scan_error", Json{std::string("wrong_output")}); + else if (blocker.scan_error) + status.emplace("scan_error", Json{static_cast(*blocker.scan_error)}); + blockers.push_back(Json{std::move(status)}); + } + return Json{Json::Object{{"ready", Json{plan.ready()}}, + {"claims_complete", Json{plan.claims_complete}}, + {"matches_census", Json{plan.matches_census(census)}}, + {"order", Json{std::move(order)}}, + {"units", Json{std::move(units)}}, + {"blockers", Json{std::move(blockers)}}}}; +} + +// verify.py attests the closed fixture and passes data only. No path in the +// manifest is opened and none of the recorded argv is run by this executable. +Json plan_fixture(const Json::Object &manifest) { + const fs::path root = string(manifest, "cwd"); + const auto &toolchain = string(manifest, "toolchain"); + const auto &revision = string(manifest, "revision"); + const auto &requested = string(manifest, "requested"); + Modules::ModuleCensus census{ + {{}, string(manifest, "compatibility"), string(manifest, "lookup")}, revision, true, {}}; + std::vector contexts; + std::vector scans; + + for (const auto &item : array(field(manifest, "members"), 5)) { + const auto &entry = object(item); + const auto &name = string(entry, "name"); + const auto &source = string(entry, "source"); + const auto &primary = string(entry, "primary_output"); + const auto &scan_revision = string(entry, "scan_revision"); + const Build::ContextKey key{ + {}, {}, Build::ContextRole::target, name, root / string(entry, "owning_source")}; + const Modules::ExpectedOutput expected{root, primary}; + const Modules::UnitInputs inputs{string(entry, "command_id"), + string(entry, "source_id"), + string(entry, "textual_closure"), + {}}; + std::vector argv; + for (const auto &argument : array(field(entry, "argv"), 64)) + argv.push_back(string(argument)); + const auto scan_filename = "scan-" + name + ".json"; + if (argv.empty() || argv.back() != source || + !std::ranges::contains(argv, "-fdeps-target=" + primary) || + !std::ranges::contains(argv, "-fdeps-file=" + scan_filename)) + throw std::runtime_error("invocation does not match scan label " + name); + + const auto method = scan_method(argv); + Build::BuildContext context; + context.key = key; + context.source_language = "c++"; + context.working_directory = root; + context.toolchain = toolchain; + context.original = + Build::OriginalCommand{root / scan_filename, scan_revision, std::move(argv), {}, {}}; + context.sources = {{key.owning_tu, key.owning_tu, Build::SourceOrigin::workspace, + Build::Editability::read_only, inputs.source}}; + contexts.push_back(std::move(context)); + + census.members.push_back({key, expected, inputs, scan_revision, {}}); + Modules::ScanEvidence scan; + scan.context = key; + scan.inputs = inputs; + scan.scan_revision = scan_revision; + scan.exit_status = exit_status(entry); + scan.rule = + Modules::decode_scan(string(field(entry, "p1689"), Modules::max_scan_bytes), expected); + scan.method = method; + scan.complete = flag(entry, "complete"); + if (flag(entry, "no_header_units")) + scan.header_uses.emplace(); + if (flag(entry, "header_provider")) + scan.provided_headers.push_back({0, key.owning_tu.string()}); + scan.writers = {(root / string(entry, "writer")).string()}; + scans.push_back(std::move(scan)); + } + + auto generation = Build::BuildGeneration::create( + {{root, "gcc-module-corpus"}, "stock-gcc-scanner", revision}, contexts); + if (!generation) + throw std::runtime_error("fixture BuildGeneration rejected"); + census.domain.generation = *generation; + for (auto &scan : scans) + scan.domain = census.domain; + const auto selected = std::ranges::find_if(census.members, [&](const auto &member) { + return member.context.alternative == requested; + }); + if (selected == census.members.end()) + throw std::runtime_error("missing requested fixture command"); + return report(Modules::build_module_plan(census, scans, selected->context), census); +} +} // namespace + +int main(int argc, char **) { + try { + if (argc != 1) + throw std::runtime_error("expected one fixture manifest on stdin"); + std::string bytes; + std::array buffer{}; + while (std::cin) { + std::cin.read(buffer.data(), buffer.size()); + bytes.append(buffer.data(), static_cast(std::cin.gcount())); + if (bytes.size() > max_manifest_bytes) + throw std::runtime_error("fixture manifest too large"); + } + if (std::cin.bad()) + throw std::runtime_error("fixture manifest read failed"); + const auto input = Protocol::parse_json(bytes, Modules::max_scan_depth); + if (!input) + throw std::runtime_error(input.error()); + const auto output = Protocol::serialize_json(plan_fixture(object(*input))); + if (!output) + throw std::runtime_error(output.error()); + if (output->size() >= max_report_bytes) + throw std::runtime_error("fixture report too large"); + std::cout << *output << '\n'; + return std::cout ? 0 : 2; + } catch (const std::exception &error) { + std::cerr << "vls_module_scan_fixture: " << error.what() << '\n'; + return 2; + } +} diff --git a/tests/modules/ModuleArtifactFixture.cpp b/tests/modules/ModuleArtifactFixture.cpp new file mode 100644 index 0000000..870ecc8 --- /dev/null +++ b/tests/modules/ModuleArtifactFixture.cpp @@ -0,0 +1,288 @@ +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace Modules = vls::modules; +namespace Build = Modules::Build; +namespace Protocol = Void::LanguageServer::Protocol; +namespace fs = std::filesystem; +using Json = Protocol::Json; + +constexpr std::size_t max_manifest_bytes = 2 * 1024 * 1024; + +const Json::Object &object(const Json &value) { + if (const auto *fields = Protocol::as_object(&value)) + return *fields; + throw std::runtime_error("expected an object"); +} + +const Json &field(const Json::Object &object, std::string_view name) { + if (const auto *value = Protocol::find_member(object, name)) + return *value; + throw std::runtime_error("missing field " + std::string(name)); +} + +const std::string &string(const Json &value, std::size_t limit = 4096) { + if (const auto *text = Protocol::as_string(&value); text && text->size() <= limit) + return *text; + throw std::runtime_error("expected a bounded string"); +} + +std::vector strings(const Json &value, std::size_t limit) { + const auto *items = Protocol::as_array(&value); + if (!items || items->size() > limit) + throw std::runtime_error("expected a bounded array"); + std::vector result; + for (const auto &item : *items) + result.push_back(string(item)); + return result; +} + +struct Unit { + std::string alternative; + Modules::ModuleCommand command; + Modules::UnitInputs inputs; +}; + +Json run(const Json::Object &manifest) { + if (const auto *mode = Protocol::as_string(Protocol::find_member(manifest, "mode")); + mode && *mode == "scan") { + namespace Sched = vls::scheduler; + const fs::path directory = string(field(manifest, "directory")); + const fs::path working = string(field(manifest, "working_directory")); + const auto command = strings(field(manifest, "command"), 1024); + const auto &output_fields = object(field(manifest, "output")); + const Modules::ExpectedOutput output{string(field(output_fields, "working_directory")), + string(field(output_fields, "spelling"))}; + auto product = std::make_shared(); + Sched::Scheduler pool{Sched::Budget{.foreground = 1, + .background = 1, + .artifact = 1, + .queued = 4, + .memory_mib = 64, + .watchdog = std::chrono::seconds{120}}}; + Modules::ModuleWorkQueue queue{pool}; + std::string failure; + auto work = Modules::gcc_module_scan_work( + [&](const Build::ContextKey &) -> std::optional { + return Modules::ScanCommand{working, command, output}; + }, + Build::ContextKey{{}, {}, Build::ContextRole::target, "scan", working / "unit.cpp"}, + product, + Modules::ScanOptions{directory, std::chrono::milliseconds{120000}, + Modules::max_scan_bytes}); + if (!queue.submit("scan-document", Modules::ModuleWorkKind::scan, 1, std::move(work), + [&](Modules::ModuleTaskResult result) { + if (result.outcome != Sched::Outcome::completed) + failure = result.detail; + })) + throw std::runtime_error("scan admission was refused"); + pool.drain(); + if (!failure.empty()) + throw std::runtime_error(failure); + Json::Array provides, imports; + for (const auto &module : product->rule->provides()) + provides.push_back(Json{module.logical_name}); + for (const auto &module : product->rule->requirements()) + imports.push_back(Json{module.logical_name}); + std::string generation; + if (!product->rule->provides().empty()) { + Modules::ArtifactCache cache{directory / "artifacts"}; + Modules::ModulePlan plan; + plan.domain.compatibility = "gcc-corpus/x86_64"; + plan.claims_complete = true; + const Build::ContextKey context{{}, {}, Build::ContextRole::target, "artifact", + working / "artifact.cpp"}; + const Modules::UnitInputs inputs{"artifact-command", "artifact-source", + "artifact-closure", {}}; + plan.units.push_back({{context, {working, "artifact.o"}, inputs, "artifact-scan", {}}, + Modules::UnitKind::primary_interface, {}}); + plan.order.push_back(context); + Modules::ModuleCommand artifact_command{ + working, {command.front(), "-std=c++26", "-fmodules-ts", "-c", command.back(), + "-o", (directory / "module.o").native()}}; + auto produced = Modules::produce_module_artifacts_scheduled( + plan, cache, directory / "artifact-staging", + Modules::gcc_module_artifact_work( + [&](const Build::ContextKey &) -> std::optional { + return artifact_command; + }), + pool); + if (!produced) + throw std::runtime_error(produced.error()); + generation = (*produced)->id(); + } + return Json{Json::Object{{"p1689", Json{product->p1689}}, + {"provides", Json{std::move(provides)}}, + {"requires", Json{std::move(imports)}}, + {"generation", Json{std::move(generation)}}}}; + } + const fs::path staging = string(field(manifest, "staging")); + const fs::path cache_path = string(field(manifest, "cache")); + const std::string &compatibility = string(field(manifest, "compatibility")); + std::vector units; + for (const auto &item : *Protocol::as_array(&field(manifest, "units"))) { + const auto &entry = object(item); + Unit unit; + unit.alternative = string(field(entry, "alternative")); + unit.command.working_directory = string(field(entry, "working_directory")); + unit.command.arguments = strings(field(entry, "command"), 1024); + unit.inputs = {string(field(entry, "command_id")), string(field(entry, "source_id")), + string(field(entry, "textual_closure")), std::nullopt}; + units.push_back(std::move(unit)); + } + if (units.empty() || units.size() > 64) + throw std::runtime_error("expected a bounded unit list"); + + Modules::ModulePlan plan; + plan.domain.compatibility = compatibility; + plan.claims_complete = true; + std::map commands; + for (const auto &unit : units) { + Build::ContextKey context{{}, + {}, + Build::ContextRole::target, + unit.alternative, + fs::path{"/fixture"} / (unit.alternative + ".cpp")}; + Modules::CensusMember member{context, + {"/fixture", unit.alternative + ".o"}, + unit.inputs, + "scan-" + unit.alternative, + {}}; + plan.units.push_back({member, Modules::UnitKind::primary_interface, {}}); + plan.order.push_back(context); + commands.emplace(unit.alternative, unit.command); + } + Modules::ArtifactCache cache{cache_path}; + const Modules::ModuleCommandLookup lookup = + [&](const Build::ContextKey &context) -> std::optional { + const auto command = commands.find(context.alternative); + if (command == commands.end()) + return std::nullopt; + return command->second; + }; + if (Protocol::as_bool(Protocol::find_member(manifest, "supersede")).value_or(false)) { + namespace Sched = vls::scheduler; + Sched::Scheduler pool{Sched::Budget{.foreground = 1, + .background = 1, + .artifact = 1, + .queued = 8, + .memory_mib = 1024, + .watchdog = std::chrono::seconds{120}}}; + std::latch started{1}; + std::mutex mutex; + std::condition_variable changed; + bool release{}; + const Modules::ArtifactWork real = Modules::gcc_module_artifact_work(lookup); + std::expected, std::string> superseded = + std::unexpected("not run"); + std::thread producer{[&] { + superseded = Modules::produce_module_artifacts_scheduled( + plan, cache, staging, + [&](std::stop_token stop, const Build::ContextKey &context, + const fs::path &output) -> std::expected { + started.count_down(); + std::unique_lock lock{mutex}; + changed.wait(lock, [&] { return release; }); + if (stop.stop_requested()) + return std::unexpected("cancelled"); + return real(stop, context, output); + }, + pool); + }}; + started.wait(); + if (!pool.submit( + {.priority = Sched::Priority::artifact, + .key = units.front().alternative, + .revision = 2, + .memory_mib = 0}, + [](std::stop_token) { return std::string{}; }, [](Sched::Result) {})) { + release = true; + changed.notify_all(); + producer.join(); + throw std::runtime_error("superseding submission was refused"); + } + { + std::lock_guard lock{mutex}; + release = true; + changed.notify_all(); + } + producer.join(); + if (superseded) + throw std::runtime_error("a superseded module build published a generation"); + if (cache.current() || cache.generations() != 0) + throw std::runtime_error("a superseded module build left artifacts behind"); + auto clean = Modules::produce_module_artifacts_scheduled( + plan, cache, staging, Modules::gcc_module_artifact_work(lookup), pool); + if (!clean) + throw std::runtime_error(clean.error()); + return Json{Json::Object{{"superseded", Json{true}}, + {"published", Json{false}}, + {"clean_generation", Json{(*clean)->id()}}}}; + } + auto produced = Modules::produce_module_artifacts(plan, cache, staging, + Modules::gcc_module_artifact_work(lookup)); + if (!produced) + throw std::runtime_error(produced.error()); + Json::Array artifacts; + for (const auto &unit : units) { + const Modules::ArtifactKey key{compatibility, unit.alternative, + unit.inputs.command + "|" + unit.inputs.source + "|" + + unit.inputs.textual_closure + "|" + + unit.inputs.system_closure.value_or(""), + "cmi"}; + const auto entry = (*produced)->find(key); + if (!entry) + throw std::runtime_error("published generation is missing " + unit.alternative); + artifacts.push_back(Json{Json::Object{{"alternative", Json{unit.alternative}}, + {"path", Json{entry->path.native()}}, + {"sha256", Json{entry->sha256}}}}); + } + return Json{Json::Object{{"generation", Json{(*produced)->id()}}, + {"artifacts", Json{std::move(artifacts)}}}}; +} +} // namespace + +int main() { + try { + std::string bytes; + char buffer[4096]; + while (std::cin) { + std::cin.read(buffer, sizeof buffer); + bytes.append(buffer, static_cast(std::cin.gcount())); + if (bytes.size() > max_manifest_bytes) + throw std::runtime_error("fixture manifest too large"); + } + if (std::cin.bad()) + throw std::runtime_error("fixture manifest read failed"); + const auto input = Protocol::parse_json(bytes, 8); + if (!input) + throw std::runtime_error(input.error()); + const auto output = Protocol::serialize_json(run(object(*input))); + if (!output) + throw std::runtime_error(output.error()); + std::cout << *output << '\n'; + return std::cout ? 0 : 2; + } catch (const std::exception &error) { + std::cerr << "vls_module_artifact_fixture: " << error.what() << '\n'; + return 2; + } +} diff --git a/tests/modules/ModuleGraphTests.cpp b/tests/modules/ModuleGraphTests.cpp new file mode 100644 index 0000000..f0584e4 --- /dev/null +++ b/tests/modules/ModuleGraphTests.cpp @@ -0,0 +1,593 @@ +#include + +#include +#include + +#include + +namespace { +using namespace vls::modules; +using Void::Testing::expect; +using Void::Testing::require; + +const ExpectedOutput invocation{"/project/private", "same.o"}; + +// The extra rule fields are literal JSON from small scanner fixtures. +std::string wire(std::string_view fields = {}) { + std::string json = R"({"version":0,"revision":0,"rules":[{"primary-output":"same.o")"; + if (!fields.empty()) { + json += ','; + json += fields; + } + return json + "}]}"; +} + +std::string named(std::string_view provision, std::vector imports = {}, + bool is_interface = true) { + std::string fields = R"("provides":[)"; + if (!provision.empty()) { + fields += R"({"logical-name":")" + std::string(provision) + R"(","is-interface":)" + + (is_interface ? "true}" : "false}"); + } + fields += R"(],"requires":[)"; + for (std::size_t i = 0; i < imports.size(); ++i) { + if (i) + fields += ','; + fields += R"({"logical-name":")" + imports[i] + R"("})"; + } + return fields + ']'; +} + +struct Fixture { + ModuleCensus census; + std::vector scans; + + explicit Fixture(std::size_t count) { + std::vector records; + for (std::size_t i = 0; i < count; ++i) { + const auto name = "unit" + std::to_string(i); + Build::BuildContext record; + record.key = {"debug", "app", Build::ContextRole::target, name, + std::filesystem::path("/project") / (name + ".cpp")}; + record.working_directory = invocation.working_directory; + record.sources.push_back({record.key.owning_tu, + {}, + Build::SourceOrigin::workspace, + Build::Editability::editable, + {}}); + CensusMember member{record.key, + invocation, + {"command:" + name, "source:" + name, "closure:" + name, {}}, + "pass-0", + {}}; + census.members.push_back(member); + records.push_back(std::move(record)); + } + const auto generation = + Build::BuildGeneration::create({{"/project", "editor"}, "fixture", "gen-1"}, records); + require(generation.has_value()); + census.domain = {*generation, "gcc16/target/stdlib/abi", "lookup-v1"}; + census.revision = "app-members-v1"; + census.closed = true; + for (const auto &member : census.members) { + ScanEvidence scan; + scan.domain = census.domain; + scan.context = member.context; + scan.inputs = member.inputs; + scan.scan_revision = member.scan_revision; + scan.exit_status = 0; + scan.rule = decode_scan(wire(), member.output); + scan.method = ScanMethod::preprocess_md; + scan.complete = true; + scan.header_uses.emplace(); + scan.writers = {"private-output:" + member.context.alternative}; + scans.push_back(std::move(scan)); + } + } + + void record(std::size_t n, std::string_view fields) { + auto &member = census.members[n]; + member.scan_revision += '+'; + auto &scan = scans[n]; + scan.scan_revision = member.scan_revision; + scan.inputs = member.inputs; + scan.domain = census.domain; + scan.rule = decode_scan(wire(fields), member.output); + require(scan.rule->has_value()); + } + void stage(std::size_t n, std::string id, std::string source) { + auto &member = census.members[n]; + member.staged_header = StagedHeader{std::move(id), std::move(source), census.domain, + member.context, member.inputs}; + } + ModulePlan plan(std::size_t n) const { + return build_module_plan(census, scans, census.members[n].context); + } + std::vector keys(std::initializer_list ids) const { + std::vector result; + for (auto i : ids) + result.push_back(census.members[i].context); + return result; + } +}; + +bool blocked(const ModulePlan &plan, PlanIssue code) { + return !plan.ready() && plan.order.empty() && + std::ranges::any_of(plan.blockers, + [code](const auto &issue) { return issue.code == code; }); +} + +const PlannedUnit &unit(const ModulePlan &plan, const Build::ContextKey &context) { + const auto it = std::ranges::find_if( + plan.units, [&](const auto &node) { return node.member.context == context; }); + require(it != plan.units.end()); + return *it; +} + +std::vector consumers(const ModulePlan &plan, const Build::ContextKey &key) { + std::vector result; + for (auto i : unit(plan, key).consumers) + result.push_back(plan.units.at(i).member.context); + return result; +} + +void rejects(std::string_view json, ScanError expected) { + auto rule = decode_scan(json, invocation); + require(!rule); + expect(rule.error() == expected); +} + +VOID_TEST(ModuleGraph, gcc_dialect_preserves_optional_lookup_and_partition_evidence) { + auto rule = decode_scan(wire(R"("work-directory":"/project/private","outputs":["other.o"], + "provides":[{"logical-name":"m:p","is-interface":false},{"logical-name":"m"}], + "requires":[{"logical-name":"","source-path":"./a/h","unique-on-source-path":true, + "lookup-method":"include-angle","compiled-module-path":"slot/opaque"}, + {"logical-name":"h","lookup-method":"include-quote"},{"logical-name":"m:p"}], + "_vendor_advisory":{"more":[true]})"), + invocation); + require(rule.has_value()); + expect(rule->output() == invocation); + expect(rule->additional_outputs() == std::vector{"other.o"}); + expect(!rule->provides()[0].is_interface && rule->provides()[1].is_interface); + const auto &entry = rule->requirements()[0]; + expect(entry.unique_on_source_path && entry.logical_name == "" && + entry.source_path == "./a/h"); + expect(entry.compiled_module_path == "slot/opaque" && + entry.lookup == LookupMethod::include_angle); + expect(rule->requirements()[1].lookup == LookupMethod::include_quote); + expect(rule->requirements()[2].lookup == LookupMethod::by_name); + rule = decode_scan(R"({"version":0,"rules":[{"primary-output":"same.o"}]})", invocation); + require(rule.has_value()); + expect(rule->provides().empty() && rule->requirements().empty() && + rule->additional_outputs().empty()); +} + +VOID_TEST(ModuleGraph, decoder_binds_exact_invocation_and_refuses_other_versions) { + rejects(R"({"version":1,"revision":0,"rules":[]})", ScanError::unsupported_version); + rejects(R"({"version":0,"revision":1,"rules":[]})", ScanError::unsupported_version); + rejects(R"({"version":"0","rules":[]})", ScanError::invalid_shape); + rejects(R"({"version":0.0,"rules":[]})", ScanError::invalid_shape); + rejects(R"({"version":0,"rules":[]})", ScanError::invalid_shape); + rejects(R"({"version":0,"rules":[{},{}]})", ScanError::invalid_shape); + rejects(R"({"version":0,"rules":[{}]})", ScanError::invalid_shape); + rejects(R"({"version":0,"rules":[{"primary-output":"./same.o"}]})", ScanError::wrong_output); + rejects(wire(R"("work-directory":"/project/link/../private")"), ScanError::wrong_directory); + auto result = decode_scan(wire(), {"relative", "same.o"}); + require(!result); + expect(result.error() == ScanError::invalid_invocation); +} + +VOID_TEST(ModuleGraph, decoder_rejects_malformed_or_unknown_semantic_fields) { + for (auto fields : + {R"("provides":null)", R"("requires":[null])", R"("requires":[{}])", + R"("requires":[{"logical-name":""}])", R"("outputs":[null])", R"("outputs":["same.o"])", + R"("outputs":["x","x"])", R"("provides":[{"logical-name":"m","is-interface":null}])", + R"("requires":[{"logical-name":"m","unique-on-source-path":true}])", + R"("requires":[{"logical-name":"m","source-path":false}])", + R"("requires":[{"logical-name":"m","compiled-module-path":17}])", + R"("requires":[{"logical-name":"m"},{"logical-name":"m"}])", + R"("requires":[{"logical-name":"m\u0000n"}])"}) + rejects(wire(fields), ScanError::invalid_shape); + for (auto fields : {R"("new-provider-semantics":true)", + R"("requires":[{"logical-name":"m","lookup-method":"another"}])", + R"("requires":[{"logical-name":"m","is-interface":false}])"}) + rejects(wire(fields), ScanError::unsupported_field); + rejects(wire(R"("requires":[],"requires":[])"), ScanError::invalid_json); + rejects("[", ScanError::invalid_json); +} + +VOID_TEST(ModuleGraph, decoder_bounds_wire_tree_strings_and_aggregate_rule_items) { + rejects(std::string(max_scan_bytes + 1, ' '), ScanError::limit); + // The envelope, rules array and its rule object account for three open containers. + auto nested = [](std::size_t depth) { + return wire(R"("_vendor_x":)" + std::string(depth, '[') + "0" + std::string(depth, ']')); + }; + expect(decode_scan(nested(max_scan_depth - 3), invocation).has_value()); + rejects(nested(max_scan_depth - 2), ScanError::limit); + expect(decode_scan(wire(named(std::string(max_field_bytes, 'a'))), invocation).has_value()); + rejects(wire(named(std::string(max_field_bytes + 1, 'a'))), ScanError::limit); + std::vector names; + for (std::size_t i = 0; i < max_rule_items; ++i) + names.push_back("m" + std::to_string(i)); + expect(decode_scan(wire(named("", names)), invocation).has_value()); + rejects(wire(named("one_more", names)), ScanError::limit); + names.push_back("beyond"); + rejects(wire(named("", names)), ScanError::limit); +} + +VOID_TEST(ModuleGraph, orders_transitive_partitions_and_retains_reverse_consumers) { + Fixture f{5}; + f.record(0, named("m:detail", {}, false)); + f.record(1, named("m:api", {"m:detail"})); + f.record(2, named("m", {"m:api"})); + f.record(3, named("", {"m", "m:detail"})); + f.census.members[4].inputs.command += " -DEXPECT_READY=48 -o importer.o"; + f.record(4, named("", {"m"})); + const auto plan = f.plan(4); + require(plan.ready()); + expect(plan.order == f.keys({0, 1, 2, 4})); + expect(consumers(plan, f.scans[0].context) == f.keys({1, 3})); + expect(consumers(plan, f.scans[2].context) == f.keys({3, 4})); + expect(unit(plan, f.scans[0].context).kind == UnitKind::internal_partition); + expect(unit(plan, f.scans[1].context).kind == UnitKind::interface_partition); + expect(unit(plan, f.scans[2].context).kind == UnitKind::primary_interface); + expect(unit(plan, f.scans[4].context).kind == UnitKind::unknown); + expect(f.plan(3).order == f.keys({0, 1, 2, 3})); + const auto request = f.scans[4].context; + std::ranges::reverse(f.census.members); + std::ranges::reverse(f.scans); + expect(plan.matches_census(f.census)); + expect(build_module_plan(f.census, f.scans, request).order == plan.order); +} + +VOID_TEST(ModuleGraph, noninterface_named_provision_requires_a_partition) { + Fixture f{2}; + f.record(0, named("m", {}, false)); + f.record(1, named("", {"m"})); + const auto invalid = f.plan(1); + expect(blocked(invalid, PlanIssue::unproven_mapping)); + expect(!invalid.claims_complete); + f.record(0, named("m:inside", {}, false)); + f.record(1, named("", {"m:inside"})); + const auto partition = f.plan(1); + require(partition.ready()); + expect(unit(partition, f.scans[0].context).kind == UnitKind::internal_partition); +} + +VOID_TEST(ModuleGraph, import_only_rules_do_not_distinguish_implementation_or_ordinary_tu) { + Fixture f{3}; + f.record(0, named("lib")); + f.record(1, named("", {"lib"})); + f.record(2, named("", {"lib"})); + auto plan = f.plan(2); + require(plan.ready()); + expect(unit(plan, f.scans[1].context).kind == UnitKind::unknown); + expect(unit(plan, f.scans[2].context).kind == UnitKind::unknown); + f.scans[1].import_only_kind = UnitKind::implementation; + f.scans[2].import_only_kind = UnitKind::ordinary; + plan = f.plan(1); + require(plan.ready()); + expect(unit(plan, f.scans[1].context).kind == UnitKind::implementation); + expect(unit(plan, f.scans[2].context).kind == UnitKind::ordinary); + f.scans[0].import_only_kind = UnitKind::implementation; + expect(blocked(f.plan(0), PlanIssue::unproven_mapping)); +} + +VOID_TEST(ModuleGraph, census_visibility_precedes_name_and_abi_compatibility) { + Fixture f{3}; + f.record(0, named("lib")); + f.record(1, named("lib")); + f.record(2, named("", {"lib"})); + expect(blocked(f.plan(2), PlanIssue::duplicate_provider)); + auto selected = f.census; + selected.members.erase(selected.members.begin() + 1); + const auto request = f.scans[2].context; + const auto chosen = build_module_plan(selected, f.scans, request); + require(chosen.ready()); + expect(chosen.order == f.keys({0, 2})); + expect(!chosen.matches_census(f.census)); + f.scans[0].domain.compatibility = "different-abi"; + expect(blocked(build_module_plan(selected, f.scans, request), PlanIssue::wrong_domain)); + f.scans[0].domain = selected.domain; + f.scans[0].domain.generation = Fixture{3}.census.domain.generation; + expect(blocked(build_module_plan(selected, f.scans, request), PlanIssue::wrong_domain)); + selected.members.erase(selected.members.begin()); + expect(blocked(build_module_plan(selected, f.scans, request), PlanIssue::missing_provider)); +} + +VOID_TEST(ModuleGraph, unknown_or_duplicate_eligible_claims_withhold_the_plan) { + Fixture f{2}; + f.record(0, named("known")); + f.record(1, named("otherwise_independent")); + require(f.plan(0).ready()); + f.scans[1].exit_status = 1; + const auto failed = f.plan(0); + expect(blocked(failed, PlanIssue::scan_failed) && !failed.claims_complete); + expect(unit(failed, f.scans[1].context).kind == UnitKind::unknown); + f.scans[1].exit_status.reset(); + expect(blocked(f.plan(0), PlanIssue::incomplete_scan)); + f.scans[1].exit_status = 0; + f.scans[1].rule.reset(); + expect(blocked(f.plan(0), PlanIssue::missing_rule)); + f.scans[1].rule = decode_scan("not JSON", invocation); + const auto invalid = f.plan(0); + expect(blocked(invalid, PlanIssue::invalid_rule)); + expect(std::ranges::any_of(invalid.blockers, [](const auto &issue) { + return issue.scan_error == ScanError::invalid_json; + })); + f.record(1, named("restored")); + f.scans.push_back(f.scans[1]); + expect(blocked(f.plan(0), PlanIssue::duplicate_scan)); + f.scans.resize(1); + expect(blocked(f.plan(0), PlanIssue::missing_scan)); + f.census.members[1].inputs.source.clear(); + expect(blocked(f.plan(0), PlanIssue::missing_source)); +} + +VOID_TEST(ModuleGraph, missing_census_authority_and_scan_freshness_are_explicit) { + Fixture f{2}; + f.census.closed = false; + expect(blocked(f.plan(0), PlanIssue::incomplete_census)); + f.census.closed = true; + f.census.members.push_back(f.census.members[1]); + expect(blocked(f.plan(0), PlanIssue::duplicate_member)); + f.census.members.pop_back(); + f.census.members[1].context.alternative = "not in provider generation"; + expect(blocked(f.plan(0), PlanIssue::invalid_context)); + f.census.members[1].context = f.scans[1].context; + f.scans[1].inputs.command += "-DOTHER"; + expect(blocked(f.plan(0), PlanIssue::stale_scan)); + f.scans[1].inputs = f.census.members[1].inputs; + f.scans[1].rule = decode_scan(wire(), {"/different/invocation", "same.o"}); + expect(blocked(f.plan(0), PlanIssue::stale_scan)); + f.scans[1].rule = decode_scan(wire(), invocation); + f.scans[1].scan_revision = "previous pass"; + expect(blocked(f.plan(0), PlanIssue::stale_scan)); + f.scans[1].scan_revision = f.census.members[1].scan_revision; + f.census.domain.lookup.clear(); + expect(blocked(f.plan(0), PlanIssue::incomplete_census)); +} + +VOID_TEST(ModuleGraph, missing_modules_and_conflicts_only_block_their_known_component) { + Fixture f{5}; + f.record(0, named("one", {"std"})); + f.record(1, named("two")); + f.record(2, named("duplicate")); + f.record(3, named("duplicate")); + f.record(4, named("", {"two"})); + expect(blocked(f.plan(0), PlanIssue::missing_provider)); + expect(blocked(f.plan(2), PlanIssue::duplicate_provider)); + expect(f.plan(4).order == f.keys({1, 4})); + f.record(0, named("", {"./include/unit.hpp"})); + expect(blocked(f.plan(0), PlanIssue::unproven_mapping)); + f.scans[0].header_uses = std::vector{{0, "header-file", "loaded-cmi"}}; + expect(blocked(f.plan(0), PlanIssue::missing_provider)); +} + +VOID_TEST(ModuleGraph, self_and_multi_node_cycles_leave_independent_tu_buildable) { + Fixture f{5}; + f.record(0, named("a", {"b"})); + f.record(1, named("b", {"a"})); + f.record(2, named("self", {"self"})); + f.record(3, named("healthy")); + f.record(4, named("", {"healthy"})); + const auto cycle = f.plan(0); + expect(blocked(cycle, PlanIssue::cycle) && cycle.claims_complete); + expect(blocked(f.plan(1), PlanIssue::cycle)); + expect(blocked(f.plan(2), PlanIssue::cycle)); + expect(f.plan(4).order == f.keys({3, 4})); +} + +VOID_TEST(ModuleGraph, renamed_provider_invalidates_an_old_plan_with_identical_membership) { + Fixture f{3}; + f.record(0, named("m")); + f.record(1, named("independent")); + f.record(2, named("", {"m"})); + const auto old = f.plan(2); + require(old.ready()); + expect(consumers(old, f.scans[1].context).empty()); + f.census.members[1].inputs.source = "edited unrelated declaration"; + f.record(1, named("m")); + expect(!old.matches_census(f.census)); + expect(blocked(f.plan(2), PlanIssue::duplicate_provider)); + expect(old.order == f.keys({0, 2})); + f.record(1, named("fixed")); + require(f.plan(2).ready()); + std::ranges::reverse(f.census.members); + auto duplicate = f.census; + duplicate.members[0] = duplicate.members[1]; + expect(!f.plan(0).matches_census(duplicate)); +} + +VOID_TEST(ModuleGraph, new_file_changes_has_include_and_adds_an_import_edge) { + Fixture f{2}; + f.record(0, named("optional")); + f.record(1, named("")); + const auto before = f.plan(1); + expect(before.order == f.keys({1})); + // The TU bytes did not change. A previously missing optional.hpp now exists and + // activates 'import optional' in the compiler scan. + f.census.domain.lookup = "lookup-v2 optional.hpp present"; + expect(!before.matches_census(f.census)); + expect(blocked(f.plan(1), PlanIssue::wrong_domain)); + f.census.members[1].inputs.textual_closure = "closure includes new optional.hpp"; + f.record(0, named("optional")); + f.record(1, named("", {"optional"})); + const auto after = f.plan(1); + expect(after.order == f.keys({0, 1})); + expect(consumers(after, f.scans[0].context) == f.keys({1})); + expect(consumers(before, f.scans[0].context).empty()); +} + +VOID_TEST(ModuleGraph, adding_an_eligible_provider_invalidates_the_previous_missing_lookup) { + Fixture f{2}; + f.record(0, named("réseau.узел")); + f.record(1, named("", {"réseau.узел"})); + auto original = f.census; + original.members.erase(original.members.begin()); + const auto &request = f.scans[1].context; + const auto missing = build_module_plan(original, f.scans, request); + expect(blocked(missing, PlanIssue::missing_provider) && missing.claims_complete); + expect(missing.matches_census(original)); + expect(!missing.matches_census(f.census)); + f.census.revision = "app-members-v2"; + expect(f.plan(1).order == f.keys({0, 1})); + f.record(1, named("", {"réseau.Узел"})); + expect(blocked(f.plan(1), PlanIssue::missing_provider)); +} + +VOID_TEST(ModuleGraph, cold_and_stale_header_cmi_cannot_attest_conditional_imports) { + Fixture f{3}; + f.record(0, named("./h")); + f.scans[0].provided_headers = {{0, "physical-header"}}; + f.record(1, named("conditioned")); + f.record(2, named("", {"./h"})); + f.scans[2].method = ScanMethod::missing_allowed; + f.scans[2].header_uses = std::vector{{0, "physical-header", {}}}; + f.scans[2].complete = false; + expect(blocked(f.plan(2), PlanIssue::incomplete_scan)); + f.scans[2].complete = true; + expect(blocked(f.plan(2), PlanIssue::stale_header)); + f.stage(0, "stage-17", "physical-header"); + (*f.scans[2].header_uses)[0].loaded_generation = "stage-17"; + const auto first = f.plan(2); + expect(first.order == f.keys({0, 2})); + f.census.members[0].inputs.textual_closure = "header and transitive macro changed to true"; + f.record(0, named("./h")); + // The process exited zero with the OLD CMI and missed 'conditioned'. + f.record(2, named("", {"./h"})); + expect(!first.matches_census(f.census)); + expect(blocked(f.plan(2), PlanIssue::stale_header)); + f.stage(0, "stage-41", "physical-header"); + expect(blocked(f.plan(2), PlanIssue::stale_header)); + (*f.scans[2].header_uses)[0].loaded_generation = "stage-41"; + f.record(2, named("", {"./h", "conditioned"})); + const auto warm = f.plan(2); + expect(warm.order == f.keys({0, 1, 2})); + expect(unit(warm, f.scans[0].context).kind == UnitKind::header_unit); + expect(first.order == f.keys({0, 2})); + f.census.members[0].staged_header->producer = f.scans[1].context; + expect(blocked(f.plan(2), PlanIssue::stale_header)); + f.stage(0, "stage-41", "physical-header"); + f.census.members[0].staged_header->domain.lookup = "stale lookup"; + expect(blocked(f.plan(2), PlanIssue::stale_header)); +} + +VOID_TEST(ModuleGraph, header_source_bindings_converge_across_spellings_and_distinguish_shadow) { + Fixture f{3}; + const auto provides = + R"("provides":[{"logical-name":"h","source-path":"./h","unique-on-source-path":true}])"; + f.record(0, provides); + f.record(1, provides); + f.scans[0].provided_headers = {{0, "first/h"}}; + f.scans[1].provided_headers = {{0, "shadow/h"}}; + f.stage(0, "first-stage", "first/h"); + f.stage(1, "shadow-stage", "shadow/h"); + f.record(2, R"("requires":[{"logical-name":"","source-path":"./selected/h", + "unique-on-source-path":true,"lookup-method":"include-angle"}, + {"logical-name":"h","source-path":"./selected/h","unique-on-source-path":true, + "lookup-method":"include-quote"}])"); + f.scans[2].header_uses = + std::vector{{0, "first/h", "first-stage"}, {1, "first/h", "first-stage"}}; + const auto first = f.plan(2); + expect(first.order == f.keys({0, 2})); + expect(consumers(first, f.scans[0].context) == f.keys({2})); + (*f.scans[2].header_uses)[1] = {1, "shadow/h", "shadow-stage"}; + expect(blocked(f.plan(2), PlanIssue::unproven_mapping)); + f.census.domain.lookup = "shadow first"; + for (auto &scan : f.scans) + scan.domain = f.census.domain; + (*f.scans[2].header_uses)[0] = {0, "shadow/h", "shadow-stage"}; + expect(blocked(f.plan(2), PlanIssue::stale_header)); + f.stage(1, "shadow-stage-2", "shadow/h"); + for (auto &use : *f.scans[2].header_uses) + use.loaded_generation = "shadow-stage-2"; + expect(f.plan(2).order == f.keys({1, 2})); + expect(!first.matches_census(f.census)); +} + +VOID_TEST(ModuleGraph, missing_header_bindings_or_artifact_path_authority_stays_pending) { + Fixture f{1}; + f.scans[0].header_uses.reset(); + expect(blocked(f.plan(0), PlanIssue::incomplete_scan)); + f.scans[0].header_uses.emplace(); + f.record(0, R"("requires":[{"logical-name":"header","lookup-method":"include-angle"}])"); + expect(blocked(f.plan(0), PlanIssue::unproven_mapping)); + f.scans[0].header_uses = std::vector{{1, "file", "one"}}; + expect(blocked(f.plan(0), PlanIssue::unproven_mapping)); + f.scans[0].header_uses = std::vector{{0, "file", "one"}, {0, "other", "two"}}; + expect(blocked(f.plan(0), PlanIssue::unproven_mapping)); + f.scans[0].header_uses->clear(); + f.record(0, R"("provides":[{"logical-name":"m","compiled-module-path":"external/unchecked"}])"); + expect(blocked(f.plan(0), PlanIssue::unproven_mapping)); +} + +VOID_TEST(ModuleGraph, mmd_requires_immutable_system_closure_and_modes_never_imply_completeness) { + Fixture f{1}; + f.scans[0].method = ScanMethod::preprocess_mmd; + expect(blocked(f.plan(0), PlanIssue::incomplete_inputs)); + f.census.members[0].inputs.system_closure = "sealed sysroot contents"; + f.record(0, named("plain")); + require(f.plan(0).ready()); + for (auto mode : + {ScanMethod::preprocess_mmd, ScanMethod::preprocess_md, ScanMethod::missing_allowed}) { + f.scans[0].method = mode; + f.scans[0].complete = false; + expect(blocked(f.plan(0), PlanIssue::incomplete_scan)); + } + f.scans[0].complete = true; + f.scans[0].method = ScanMethod::unknown; + expect(blocked(f.plan(0), PlanIssue::incomplete_scan)); +} + +VOID_TEST(ModuleGraph, actual_writer_identity_distinguishes_private_outputs_from_collisions) { + Fixture f{3}; + f.record(0, R"("outputs":["private-extra"])"); + f.scans[0].writers.push_back("verified shared destination"); + const auto private_outputs = f.plan(0); + require(private_outputs.ready()); + expect(f.census.members[0].output == f.census.members[1].output); + f.scans[1].writers[0] = "verified shared destination"; + expect(blocked(f.plan(0), PlanIssue::writer_collision)); + expect(blocked(f.plan(1), PlanIssue::writer_collision)); + expect(f.plan(2).order == f.keys({2})); + f.scans[0].writers.pop_back(); + expect(blocked(f.plan(0), PlanIssue::unproven_mapping)); +} + +VOID_TEST(ModuleGraph, deep_legal_chain_orders_once_and_graph_limits_fail_closed) { + Fixture f{max_units}; + for (std::size_t i = 0; i < max_units; ++i) { + std::vector imports; + if (i) + imports.push_back("m" + std::to_string(i - 1)); + f.record(i, named("m" + std::to_string(i), imports)); + } + const auto plan = f.plan(max_units - 1); + require(plan.ready() && plan.order.size() == max_units); + bool ordered = true; + for (std::size_t i = 0; i < max_units; ++i) + ordered &= plan.order[i] == f.scans[i].context; + expect(ordered); + f.census.members.push_back(f.census.members[0]); + expect(blocked(f.plan(0), PlanIssue::limit)); + f.census.members.pop_back(); + f.scans[0].writers.front().resize(max_field_bytes + 1, 'x'); + expect(blocked(f.plan(0), PlanIssue::limit)); + f.scans[0].writers.front() = "restored"; + for (auto &member : f.census.members) + member.inputs.textual_closure.resize(max_field_bytes, 'x'); + expect(blocked(f.plan(0), PlanIssue::limit)); +} + +VOID_TEST(ModuleGraph, aggregate_edge_budget_is_enforced_before_resolution) { + Fixture f{80}; + std::vector names(450); + for (std::size_t i = 0; i < names.size(); ++i) + names[i] = "m" + std::to_string(i); + const auto fields = named("", names); + for (std::size_t i = 0; i < f.scans.size(); ++i) + f.record(i, fields); + expect(blocked(f.plan(0), PlanIssue::limit)); +} +} // namespace diff --git a/tests/modules/ModuleWorkQueueTests.cpp b/tests/modules/ModuleWorkQueueTests.cpp new file mode 100644 index 0000000..2b3fc0e --- /dev/null +++ b/tests/modules/ModuleWorkQueueTests.cpp @@ -0,0 +1,198 @@ +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace vls::modules; +namespace Sched = vls::scheduler; +using namespace std::chrono_literals; +using Void::Testing::expect; +using Void::Testing::require; + +constexpr Sched::Budget budget{ + .foreground = 1, .background = 1, .artifact = 1, .queued = 8, .memory_mib = 64, .watchdog = 5s}; + +struct Gate { + std::mutex mutex; + std::condition_variable changed; + bool open{}; + void wait() { + std::unique_lock lock{mutex}; + changed.wait(lock, [&] { return open; }); + } + void release() { + std::lock_guard lock{mutex}; + open = true; + changed.notify_all(); + } +}; + +struct Results { + mutable std::mutex mutex; + std::condition_variable changed; + std::vector values; + + void add(ModuleTaskResult result) { + std::lock_guard lock{mutex}; + values.push_back(std::move(result)); + changed.notify_all(); + } + std::optional wait(std::string_view document, ModuleWorkKind kind, + std::uint64_t revision, + std::chrono::milliseconds timeout = 5000ms) { + std::unique_lock lock{mutex}; + changed.wait_for(lock, timeout, [&] { + for (const auto &result : values) + if (result.document == document && result.kind == kind && + result.revision == revision) + return true; + return false; + }); + for (const auto &result : values) + if (result.document == document && result.kind == kind && result.revision == revision) + return result; + return std::nullopt; + } + std::size_t size() const { + std::lock_guard lock{mutex}; + return values.size(); + } +}; + +ModuleWork cooperative(std::atomic &started, std::string detail = "stopped") { + return [&started, detail](std::stop_token token) { + started = true; + std::mutex mutex; + std::condition_variable changed; + bool stopped{}; + std::stop_callback callback{token, [&] { + std::lock_guard lock{mutex}; + stopped = true; + changed.notify_all(); + }}; + std::unique_lock lock{mutex}; + changed.wait(lock, [&] { return stopped; }); + return detail; + }; +} + +template +bool eventually(Predicate predicate, std::chrono::milliseconds timeout = 5000ms) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (std::chrono::steady_clock::now() < deadline) { + if (predicate()) + return true; + std::this_thread::sleep_for(1ms); + } + return predicate(); +} +} // namespace + +VOID_TEST(ModuleWorkQueue, priorities_are_separated) { + Sched::Scheduler scheduler{budget}; + ModuleWorkQueue queue{scheduler}; + Gate gate; + Results results; + std::atomic first_started{}, second_started{}; + queue.submit( + "a", ModuleWorkKind::scan, 1, + [&](std::stop_token) { + first_started = true; + gate.wait(); + return std::string{"held"}; + }, + [&](ModuleTaskResult result) { results.add(std::move(result)); }); + require(eventually([&] { return first_started.load(); })); + require(queue.submit( + "b", ModuleWorkKind::scan, 1, + [&](std::stop_token) { + second_started = true; + return std::string{}; + }, + [&](ModuleTaskResult result) { results.add(std::move(result)); })); + require(queue.submit( + "c", ModuleWorkKind::artifact, 1, [](std::stop_token) { return std::string{"artifact"}; }, + [&](ModuleTaskResult result) { results.add(std::move(result)); })); + const auto artifact = results.wait("c", ModuleWorkKind::artifact, 1); + require(artifact.has_value()); + expect(artifact->outcome == Sched::Outcome::completed); + expect(!second_started.load()); + gate.release(); + scheduler.drain(); + expect(second_started.load()); +} + +VOID_TEST(ModuleWorkQueue, newer_revision_supersedes) { + Sched::Scheduler scheduler{budget}; + ModuleWorkQueue queue{scheduler}; + Results results; + std::atomic started{}; + require(queue.submit("document", ModuleWorkKind::scan, 1, cooperative(started), + [&](ModuleTaskResult result) { results.add(std::move(result)); })); + require(eventually([&] { return started.load(); })); + require(queue.submit( + "document", ModuleWorkKind::scan, 2, [](std::stop_token) { return std::string{"second"}; }, + [&](ModuleTaskResult result) { results.add(std::move(result)); })); + const auto first = results.wait("document", ModuleWorkKind::scan, 1); + require(first.has_value()); + expect(first->outcome == Sched::Outcome::cancelled); + const auto second = results.wait("document", ModuleWorkKind::scan, 2); + require(second.has_value()); + expect(second->outcome == Sched::Outcome::completed); +} + +VOID_TEST(ModuleWorkQueue, cancel_document_stops_both_kinds) { + Sched::Scheduler scheduler{budget}; + ModuleWorkQueue queue{scheduler}; + Results results; + std::atomic scan_started{}, artifact_started{}; + require(queue.submit("document", ModuleWorkKind::scan, 1, cooperative(scan_started), + [&](ModuleTaskResult result) { results.add(std::move(result)); })); + require(queue.submit("document", ModuleWorkKind::artifact, 1, cooperative(artifact_started), + [&](ModuleTaskResult result) { results.add(std::move(result)); })); + require(eventually([&] { return scan_started.load() && artifact_started.load(); })); + queue.cancel("document"); + const auto scan = results.wait("document", ModuleWorkKind::scan, 1); + const auto artifact = results.wait("document", ModuleWorkKind::artifact, 1); + require(scan.has_value() && artifact.has_value()); + expect(scan->outcome == Sched::Outcome::cancelled); + expect(artifact->outcome == Sched::Outcome::cancelled); + scheduler.drain(); +} + +VOID_TEST(ModuleWorkQueue, refuses_stale_revisions) { + Sched::Scheduler scheduler{budget}; + ModuleWorkQueue queue{scheduler}; + require(queue.submit("document", ModuleWorkKind::scan, 2, + [](std::stop_token) { return std::string{}; })); + expect(!queue.submit("document", ModuleWorkKind::scan, 1, + [](std::stop_token) { return std::string{}; })); + expect( + !queue.submit("", ModuleWorkKind::scan, 3, [](std::stop_token) { return std::string{}; })); + scheduler.drain(); +} + +VOID_TEST(ModuleWorkQueue, counts_track_terminal_outcomes) { + Sched::Scheduler scheduler{budget}; + ModuleWorkQueue queue{scheduler}; + require( + queue.submit("ok", ModuleWorkKind::scan, 1, [](std::stop_token) { return std::string{}; })); + require(queue.submit("failed", ModuleWorkKind::artifact, 1, + [](std::stop_token) -> std::string { throw std::runtime_error{"boom"}; })); + scheduler.drain(); + const auto counts = queue.counts(); + expect(counts.submitted == 2 && counts.completed == 1 && counts.failed == 1 && + counts.cancelled == 0); +} diff --git a/tests/modules/ScanCommandTests.cpp b/tests/modules/ScanCommandTests.cpp new file mode 100644 index 0000000..475942a --- /dev/null +++ b/tests/modules/ScanCommandTests.cpp @@ -0,0 +1,52 @@ +#include + +#include +#include + +#include +#include +#include + +namespace { +using namespace vls::modules; +using Void::Testing::expect; +using Void::Testing::require; + +Build::BuildContext context(std::vector arguments) { + Build::BuildContext row; + row.key = {{}, {}, Build::ContextRole::target, "unit", "/project/unit.cpp"}; + row.working_directory = "/project"; + row.semantic_arguments = std::move(arguments); + return row; +} +} // namespace + +VOID_TEST(ScanCommand, derives_a_bounded_p1689_invocation) { + auto row = context({"/tool/g++", "-std=c++26", "-I", "/include", "-c", "/project/unit.cpp", + "-o", "/out/unit.o", "-fdeps-format=p1689r5"}); + auto built = build_scan_invocation(row, {"/project", "unit.o"}, "/private/deps.json"); + require(built.has_value()); + const auto &arguments = built->arguments; + expect(arguments.front() == "/tool/g++"); + expect(std::ranges::find(arguments, std::string{"-c"}) == arguments.end()); + expect(std::ranges::find(arguments, std::string{"/out/unit.o"}) == arguments.end()); + expect(std::ranges::find(arguments, std::string{"/include"}) != arguments.end()); + expect(std::ranges::find(arguments, std::string{"-fdeps-file=/private/deps.json"}) != + arguments.end()); + expect(std::ranges::find(arguments, std::string{"-fdeps-target=unit.o"}) != arguments.end()); + expect(arguments.back() == "/project/unit.cpp"); +} + +VOID_TEST(ScanCommand, refuses_missing_duplicate_or_relative_inputs) { + const ExpectedOutput output{"/project", "unit.o"}; + expect( + !build_scan_invocation(context({"/tool/g++"}), output, "/private/deps.json").has_value()); + expect(!build_scan_invocation(context({"/tool/g++", "/project/unit.cpp", "/project/unit.cpp"}), + output, "/private/deps.json") + .has_value()); + expect( + !build_scan_invocation(context({"/tool/g++", "/project/unit.cpp"}), output, "relative.json") + .has_value()); + Build::BuildContext empty; + expect(!build_scan_invocation(empty, output, "/private/deps.json").has_value()); +} diff --git a/tests/native/DapReplay.py b/tests/native/DapReplay.py new file mode 100644 index 0000000..c64415e --- /dev/null +++ b/tests/native/DapReplay.py @@ -0,0 +1,319 @@ +"""Exercise a VLS debug adapter on recorded GCC events using the public stdio protocol.""" + +import argparse +import hashlib +import json +import queue +import shutil +import subprocess +import tempfile +import threading +from pathlib import Path + + +class Client: + def __init__(self, adapter, trace): + self.child = subprocess.Popen( + [adapter, "--replay", trace], cwd=trace.parent, env={"PATH": "", "LC_ALL": "C"}, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + self.incoming = queue.Queue() + self.reader = threading.Thread(target=self._read, daemon=True) + self.reader.start() + self.outgoing_seq = 0 + self.incoming_seq = 0 + + def _read(self): + try: + stream = self.child.stdout + while line := stream.readline(8192): + assert line.startswith(b"Content-Length: ") and line.endswith(b"\r\n"), line + length = int(line[16:]) + assert 0 < length <= 16 * 1024 * 1024 and stream.readline(8192) == b"\r\n" + self.incoming.put(json.loads(stream.read(length))) + self.incoming.put(EOFError("adapter stdout closed")) + except Exception as error: + self.incoming.put(error) + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.child.stdin.close() + if self.child.poll() is None: + self.child.kill() + self.child.wait(timeout=5) + self.reader.join(timeout=5) + self.child.stdout.close() + self.child.stderr.close() + + def send(self, command, args=None): + self.outgoing_seq += 1 + message = {"seq": self.outgoing_seq, "type": "request", "command": command, + "arguments": {} if args is None else args} + body = json.dumps(message).encode() + self.child.stdin.write(f"Content-Length: {len(body)}\r\n\r\n".encode() + body) + self.child.stdin.flush() + return self.outgoing_seq + + def receive(self): + message = self.incoming.get(timeout=5) + if isinstance(message, Exception): + raise message + self.incoming_seq += 1 + assert message["seq"] == self.incoming_seq, message + assert "jsonrpc" not in message, message + return message + + def response(self, seq, command, success=True): + reply = self.receive() + assert (reply["type"], reply["request_seq"], reply["command"], reply["success"]) == ( + "response", seq, command, success), reply + return reply.get("body", {}) + + def request(self, command, args=None, success=True): + return self.response(self.send(command, args), command, success) + + def event(self, name): + event = self.receive() + assert event["type"] == "event" and event["event"] == name, event + return event.get("body", {}) + + def initialize(self, paging=True): + caps = self.request("initialize", {"adapterID": "vls", "supportsVariablePaging": paging}) + assert caps["supportsConfigurationDoneRequest"] and caps["supportsLoadedSourcesRequest"] + assert not caps.get("supportsStepBack") + self.event("initialized") + + def launch(self, paging=True): + self.initialize(paging) + launch = self.send("launch") + self.request("configurationDone") + self.response(launch, "launch") + self.stopped() + return self.request("vls/session") + + def stopped(self): + stopped = self.event("stopped") + assert stopped["threadId"] == 1 and stopped["allThreadsStopped"] + + def disconnect(self, terminated=False): + self.request("disconnect") + if not terminated: + self.event("terminated") + assert self.child.wait(timeout=5) == 0 + assert self.child.stderr.read() == b"" + assert isinstance(self.incoming.get(timeout=5), EOFError), "extra adapter output" + + +def identity(state): + return {key: state[key] for key in ("schemaVersion", "sessionId", "generation")} + + +def page(client, command, state, start=0, count=64): + reply = client.request(command, {**identity(state), "start": start, "count": count}) + assert identity(reply) == identity(state) + return reply + + +def seek(client, state, **destination): + reply = client.request("vls/seek", {**identity(state), **destination}) + client.stopped() + current = client.request("vls/session") + assert identity(current) == identity(reply) + assert current["generation"] > state["generation"] + return current + + +def inspect_value(client, expected): + stack = client.request("stackTrace", {"threadId": 1}) + frames = stack["stackFrames"] + assert stack["totalFrames"] == len(frames) and len(frames) >= 1 + assert all(f["line"] == 0 and f["column"] == 0 and "source" not in f for f in frames) + top = frames[0]["id"] + scopes = client.request("scopes", {"frameId": top})["scopes"] + ref = scopes[0]["variablesReference"] + assert ref > 0 and ref != top + variables = client.request("variables", {"variablesReference": ref})["variables"] + assert [v["value"] for v in variables if v["name"] == "Result"] == [str(expected)], variables + return top, ref + + +def replay(adapter, selected, replacement, work, expected): + private = work / "selected.vls" + shutil.copyfile(selected, private) + with Client(adapter, private) as client: + state = client.launch() + assert state["mode"] == "replay" and state["pauseKind"] == "recordedStop" + assert state["schemaVersion"] == 1 and state["eventSequence"] == 6 + assert state["recording"]["outcome"] == "completed" and state["recording"]["exitCode"] == 0 + assert not state["recording"]["partial"] and not state["recording"]["corrupt"] + session_id = state["sessionId"] + top, scope = inspect_value(client, expected) + source = client.request("loadedSources")["sources"] + assert len(source) == 1 and "path" not in source[0] + ref = source[0]["sourceReference"] + assert ref == state["sourceReference"] and ref > 0 + source_args = {"sourceReference": ref, "source": {"path": str(replacement)}} + captured = client.request("source", source_args)["content"].encode() + assert f"Ready = {expected}".encode() in captured + assert len(captured) == state["sourceByteLength"] + assert hashlib.sha256(captured).hexdigest() == state["sourceSha256"] + client.request("source", {**source_args, "source": {"sourceReference": ref + 1}}, False) + client.request("source", {"sourceReference": 0, "source": {"path": str(replacement)}}, False) + + # Later requests must use the bytes and index acquired on launch. + newer = work / "new.vls" + shutil.copyfile(replacement, newer) + newer.replace(private) + private.unlink() + assert client.request("source", source_args)["content"].encode() == captured + events = page(client, "vls/timeline", state) + assert events["total"] == len(events["events"]) == state["recording"]["eventCount"] + indexed = {event["sequence"]: event for event in events["events"]} + assert (indexed[7]["acknowledgedStop"], indexed[7]["acknowledgedAction"]) == (6, "step") + assert (indexed[11]["acknowledgedStop"], indexed[11]["acknowledgedAction"]) == (10, "continue") + assert page(client, "vls/timeline", state, events["total"], 0)["events"] == [] + for bad_page in ({"count": 257}, {"count": -1}, {"start": events["total"] + 1}, + {"start": 0.5}, {"sessionId": "other"}, {"schemaVersion": 2}): + args = {**identity(state), "start": 0, "count": 1, **bad_page} + client.request("vls/timeline", args, False) + view = page(client, "vls/frames", state) + assert [f["name"] for f in view["frames"]] == ["reflected_value", "twice"] + assert view["frames"][0]["sourceKind"] == "logicalDeclaration" + first = state + state = seek(client, state, eventSequence=5) + view = page(client, "vls/frames", state) + assert state["pauseKind"] == "value" and view["stop"] is None + assert view["frames"][0]["valueProvisional"] and view["lastLeave"] is None + state = seek(client, state, eventSequence=8) + view = page(client, "vls/frames", state) + assert [f["name"] for f in view["frames"]] == ["twice"] + assert view["lastLeave"]["outcome"] == "returned" and not view["lastLeave"]["valueProvisional"] + state = seek(client, state, direction="previousValue") + assert state["eventSequence"] == 6 and state["sessionId"] == session_id + assert inspect_value(client, expected)[0] != top + client.request("scopes", {"frameId": top}, False) + client.request("variables", {"variablesReference": scope}, False) + client.request("vls/frames", {**identity(first), "start": 0, "count": 1}, False) + client.request("vls/seek", {**identity(first), "eventSequence": 10}, False) + client.request("continue", {"threadId": 1, "vlsContext": identity(first)}, False) + client.request("next", {"threadId": 1}, False) + for value, sequence, kind in ((expected * 2, 10, "recordedStop"), + (expected + 5, 20, "value"), ((expected + 5) * 2, 22, "value")): + client.request("continue", {"threadId": 1, "vlsContext": identity(state)}) + client.stopped() + state = client.request("vls/session") + assert (state["eventSequence"], state["pauseKind"]) == (sequence, kind) + inspect_value(client, value) + client.request("continue", {"threadId": 1}) + client.event("terminated") + client.disconnect(terminated=True) + return session_id + + +def cancelled(adapter, fixture): + with Client(adapter, fixture) as client: + state = client.launch() + assert state["recording"]["outcome"] == "cancelled" and state["recording"]["exitCode"] == 125 + assert state["recording"]["partial"] and not state["recording"]["corrupt"] + inspect_value(client, 41) + events = page(client, "vls/timeline", state)["events"] + assert events[-1]["sequence"] == 7 and events[-1]["kind"] == "terminal" + client.request("continue", {"threadId": 1}) + client.event("terminated") + client.disconnect(terminated=True) + + +def failures(adapter, valid, work): + invalid = work / "invalid.vls" + invalid.write_bytes(b"invalid") + with Client(adapter, invalid) as client: + client.initialize() + client.request("launch", {"trace": str(valid)}, False) + client.request("launch", success=False) + client.disconnect() + with Client(adapter, valid) as client: + client.initialize() + for invalid_option in (True, "false", None): + client.request("launch", {"noDebug": invalid_option}, False) + client.request("configurationDone") + client.request("launch", {"noDebug": False}) + client.stopped() + client.disconnect() + peer_reply = b'{"seq":3,"type":"response","request_seq":1,"command":"initialize","success":true}' + reply_frame = f"Content-Length: {len(peer_reply)}\r\n\r\n".encode() + peer_reply + for raw in (b"Content-Length: 20\r\n\r\n{}", b"Content-Length: 3\r\n\r\nabc", + b"Content-Length: 1\r\nContent-Length: 1\r\n\r\n0", b"Content-Len", reply_frame): + child = subprocess.run([adapter, "--replay", valid], input=raw, capture_output=True, + env={"PATH": ""}, timeout=5) + assert child.returncode != 0 and not child.stdout and child.stderr + with Client(adapter, valid) as client: + client.initialize() + pending = client.send("launch") + client.child.stdin.write(raw) + client.child.stdin.close() + client.response(pending, "launch", False) + assert client.child.wait(timeout=5) != 0 + assert isinstance(client.incoming.get(timeout=5), EOFError) + + +def incomplete_and_paging(adapter, valid, work): + raw = valid.read_bytes() + assert hashlib.sha256(raw).hexdigest() == "4efd70044105ed7e2ae1104780e564d1b8e20bc7d9494f3e0ed82156cef95ea4" + # The original recording reaches the second function body at this record boundary. + prefix = work / "before-first-return.vls" + prefix.write_bytes(raw[:1995]) + with Client(adapter, prefix) as client: + state = client.launch() + assert state["eventSequence"] == 4 and state["pauseKind"] == "event" + assert state["recording"]["partial"] and state["recording"]["eventCount"] == 5 + state = seek(client, state, eventSequence=1) + assert [f["name"] for f in page(client, "vls/frames", state)["frames"]] == ["twice"] + client.disconnect() + for paged in (False, True): + with Client(adapter, valid) as client: + client.launch(paged) + _, ref = inspect_value(client, 17) + var_args = {"variablesReference": ref} + all_vars = client.request("variables", var_args)["variables"] + subset = client.request("variables", {**var_args, "start": 1, "count": 1})["variables"] + assert subset == (all_vars[1:2] if paged else all_vars) + assert client.request("stackTrace", {"threadId": 1, "startFrame": 2**32-1})["stackFrames"] == [] + if paged: + assert client.request("variables", {**var_args, "start": 2**32-1})["variables"] == [] + for breakpoint in ({}, {"line": "5"}, {"line": 3, "column": -1}): + client.request("setBreakpoints", {"source": {}, "breakpoints": [breakpoint]}, False) + client.disconnect() + with Client(adapter, valid) as client: + client.initialize() + seq = client.send("launch") + client.outgoing_seq -= 1 # A second packet reuses the outstanding launch correlation. + assert client.send("launch") == seq + client.response(seq, "launch", False) + assert client.child.wait(timeout=5) != 0 + assert isinstance(client.incoming.get(timeout=5), EOFError), "duplicate launch response" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--adapter", required=True, type=Path) + parser.add_argument("--fixtures", type=Path, + default=Path(__file__).resolve().parents[1] / "debug" / "fixtures") + args = parser.parse_args() + adapter = args.adapter.resolve(strict=True) + a, b, c = (args.fixtures.resolve() / name for name in + ("integral-17.vls", "integral-41.vls", "cancelled-41.vls")) + with tempfile.TemporaryDirectory(prefix="vls-dap-") as directory: + work = Path(directory) + first = replay(adapter, a, b, work, 17) + second = replay(adapter, b, a, work, 41) + assert first != second + cancelled(adapter, c) + failures(adapter, a, work) + incomplete_and_paging(adapter, a, work) + print("DAP replay passed: 17/34/22/44, 41/82/46/92, cancelled prefix 41, expired " + "handles and pages, immutable source, ordered acknowledgements and malformed frames") + + +if __name__ == "__main__": + main() diff --git a/tests/native/EditorModules.py b/tests/native/EditorModules.py new file mode 100644 index 0000000..d7669dd --- /dev/null +++ b/tests/native/EditorModules.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Exercise EditorDiagnostics module scan and artifact preparation with real GCC.""" + +import argparse +import json +import os +from pathlib import Path +import select +import subprocess +import tempfile +import time + + +def check(condition, detail): + if not condition: + raise ValueError(detail) + + +def frame(message): + payload = json.dumps({"jsonrpc": "2.0", **message}, ensure_ascii=False).encode() + return f"Content-Length: {len(payload)}\r\n\r\n".encode() + payload + + +class Session: + def __init__(self, argv, cwd, stderr): + self.process = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=stderr, + env={**os.environ, "LC_ALL": "C"}) + self.sequence = 0 + self.buffer = b"" + + def send(self, message): + self.process.stdin.write(frame(message)) + self.process.stdin.flush() + + def notify(self, method, params): + self.send({"method": method, "params": params}) + + def request(self, method, params, timeout=180): + self.sequence += 1 + self.send({"id": self.sequence, "method": method, "params": params}) + deadline = time.monotonic() + timeout + while True: + message = self.read(deadline - time.monotonic()) + if message.get("id") == self.sequence: + return message + + def read(self, timeout): + check(timeout > 0, "LSP response deadline expired") + while b"\r\n\r\n" not in self.buffer: + ready, _, _ = select.select([self.process.stdout], [], [], timeout) + check(ready, "LSP response deadline expired") + chunk = os.read(self.process.stdout.fileno(), 65536) + check(chunk, "the server closed stdout") + self.buffer += chunk + header, rest = self.buffer.split(b"\r\n\r\n", 1) + length = int(header.removeprefix(b"Content-Length: ")) + while len(rest) < length: + chunk = os.read(self.process.stdout.fileno(), 65536) + check(chunk, "truncated LSP response") + rest += chunk + body, self.buffer = rest[:length], rest[length:] + return json.loads(body) + + def close(self): + try: + self.request("shutdown", None, timeout=30) + self.notify("exit", None) + except (OSError, ValueError, TimeoutError): + pass + try: + self.process.stdin.close() + except OSError: + pass + try: + self.process.wait(timeout=10) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + + +def await_field(session, uri, field, predicate, timeout=180): + deadline = time.monotonic() + timeout + last = None + result = None + while time.monotonic() < deadline: + reply = session.request("voidLanguageServer/analysisStatus", + {"textDocument": {"uri": uri}}, timeout=30) + result = reply.get("result") or {} + last = result.get(field) + if last and predicate(last): + return last + if last and last.get("state") in ("failed", "unavailable", "cancelled"): + raise ValueError(f"{field} did not complete: {last} status={result}") + time.sleep(0.2) + raise ValueError(f"{field} did not finish: {last} status={result}") + + +def run(server, profile, compiler, observer): + with tempfile.TemporaryDirectory(prefix="vls-editor-modules-") as temp: + root = Path(temp) + source = root / "editor.cmi.cpp" + source.write_text("export module editor.cmi;\n" + "export int twice(int value) { return value * 2; }\n", + encoding="utf-8") + object_path = root / "editor.cmi.o" + database = root / "compile_commands.json" + database.write_text(json.dumps([{ + "directory": str(root), "file": str(source), + "arguments": [str(compiler), "-std=c++26", "-fmodules-ts", "-c", str(source), "-o", + str(object_path)]}])) + uri = source.as_uri() + text = source.read_text(encoding="utf-8") + with tempfile.TemporaryFile() as errors: + session = Session([str(server), "--stdio", "--workspace-root", str(root), + "--provider", "compdb", "--compdb", str(database), + "--gcc-profile", str(profile)], root, errors) + try: + initialized = session.request("initialize", { + "processId": None, "capabilities": {}, + "workspaceFolders": [{"uri": root.as_uri(), "name": root.name}]}) + check(initialized["result"]["capabilities"].get("hoverProvider"), + "observer capabilities are not advertised") + session.notify("initialized", {}) + session.notify("textDocument/didOpen", {"textDocument": { + "uri": uri, "languageId": "cpp", "version": 1, "text": text}}) + scan = await_field(session, uri, "moduleScan", + lambda value: value.get("state") in ("ready", "partial")) + check("editor.cmi" in scan.get("provides", []), f"wrong scan: {scan}") + artifact = await_field(session, uri, "moduleArtifact", + lambda value: value.get("state") == "ready") + check(len(artifact.get("generation", "")) == 64, + f"no published artifact generation: {artifact}") + finally: + session.close() + errors.seek(0) + diagnostics = errors.read() + check(b"fatal" not in diagnostics.lower(), diagnostics[-800:]) + print(f"editor modules: scan provided editor.cmi, artifact generation " + f"{artifact['generation'][:16]}...") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--server", required=True, type=Path) + parser.add_argument("--gcc-profile", required=True, type=Path) + parser.add_argument("--cxx", default="g++") + parser.add_argument("--observer", type=Path, + help="assert this observer is selected by the profile") + options = parser.parse_args() + compiler = Path(shutil_which(options.cxx)) + run(options.server.resolve(strict=True), options.gcc_profile.resolve(strict=True), + compiler.resolve(strict=True), options.observer) + + +def shutil_which(name): + from shutil import which + selected = which(name) + check(selected, f"{name} was not found") + return selected + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, subprocess.SubprocessError) as exc: + raise SystemExit(f"verify-editor-modules: {exc}") diff --git a/tests/native/GccLeaf.py b/tests/native/GccLeaf.py new file mode 100644 index 0000000..8ef1e7b --- /dev/null +++ b/tests/native/GccLeaf.py @@ -0,0 +1,156 @@ +"""Check the private Linux GCC launcher with a harmless ELF and the patched frontend.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import select +import shutil +import subprocess +import tempfile + + +NONCE = "146a66737eef9c04ea33c6e05589f701" +ROOT = Path(__file__).resolve().parents[2] +WITNESS = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv, char **env) { + const char *fixed[] = {"cc1plus", "-quiet", "-std=c++26", "-freflection", "-fsyntax-only", + "-nostdinc", "-o", "/dev/null", "-fvls-observe", "-fvls-step", "input.cpp"}; + if (argc != 11) return 10; + for (int i = 0; i < argc; ++i) + if (strcmp(fixed[i], argv[i])) return 11; + const char *nonce = getenv("VLS_GCC_NONCE"); + if (!nonce || !getenv("LC_ALL") || strcmp("C", getenv("LC_ALL")) || + !getenv("PATH") || *getenv("PATH") || getenv("VLS_TEST_PARENT_ONLY")) return 12; + int count = 0; + while (env[count]) ++count; + if (count != 3) return 13; + struct stat raw_in, raw_out, err, control, events; + if (fstat(0, &raw_in) || fstat(1, &raw_out) || fstat(2, &err) || + fstat(3, &control) || fstat(4, &events)) return 14; + if (!S_ISCHR(raw_in.st_mode) || raw_in.st_rdev != makedev(1,3) || + raw_out.st_rdev != raw_in.st_rdev || !S_ISFIFO(err.st_mode) || + !S_ISFIFO(control.st_mode) || !S_ISFIFO(events.st_mode) || + control.st_ino == events.st_ino || err.st_ino == events.st_ino) return 15; + for (int fd = 5; fd < 32; ++fd) + if (fcntl(fd, F_GETFD) >= 0) return 16; + struct rlimit core, cpu, memory, files, descriptors; + if (getrlimit(RLIMIT_CORE, &core) || getrlimit(RLIMIT_CPU, &cpu) || + getrlimit(RLIMIT_FSIZE, &files) || getrlimit(RLIMIT_AS, &memory) || + getrlimit(RLIMIT_NOFILE, &descriptors)) return 17; + if (core.rlim_max || cpu.rlim_cur > 15 || cpu.rlim_max > 20 || + memory.rlim_max > 768ULL * 1024 * 1024 || files.rlim_max > 1024 * 1024 || + descriptors.rlim_max > 32) return 18; + int self = open("/proc/self/exe", O_RDONLY); + int seals = fcntl(self, F_GET_SEALS); + int required = F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL; + if (seals < 0 || (seals & required) != required) return 19; + close(self); + dprintf(1, "discarded raw output\n"); + dprintf(2, "witness diagnostic\n"); + dprintf(4, "%s\n", nonce); + char go; + if (read(3, &go, 1) != 1 || go != 'g') return 20; + dprintf(4, "same sealed executable\n"); + return 0; +} +""" + + +def digest(path): + with path.open("rb") as file: + return hashlib.file_digest(file, "sha256").hexdigest() + + +def require(ok, message): + if not ok: + raise ValueError(message) + + +def args(probe, compiler, sha, nonce=NONCE, mode="step"): + return [str(probe), "--leaf", str(compiler), sha, nonce, mode] + + +def verify_leaf(probe, compiler, cc, work): + source = work / "witness.c" + source.write_text(WITNESS) + witness = work / "witness" + subprocess.run([cc, str(source), "-o", str(witness)], check=True, timeout=30) + sha = digest(witness) + saved = work / "original-witness" + env = {**os.environ, "VLS_TEST_PARENT_ONLY": "must not reach compiler"} + with subprocess.Popen(args(probe, witness, sha), stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, cwd=work, env=env, bufsize=0) as child: + try: + require(select.select([child.stdout], [], [], 5)[0], "witness did not start") + require(child.stdout.readline() == NONCE.encode() + b"\n", "sealed ELF did not verify process state") + witness.rename(saved) + witness.write_bytes(b"this file cannot be a compiler") + out, err = child.communicate(b"g", timeout=5) + require((out, err, child.returncode) == (b"same sealed executable\n", b"witness diagnostic\n", 0), + f"unexpected witness output {out!r}, {err!r}, {child.returncode}") + finally: + if child.poll() is None: + child.kill() + child.wait(timeout=3) + print("Verified fixed argv, pipe identity, resource limits, environment and sealed execution after replacement") + + script = work / "benign.sh" + script.write_text("#!/bin/sh\nexit 0\n") + script.chmod(0o700) + partial = work / "partial" + partial.write_bytes(saved.read_bytes()[:-24]) + partial.chmod(0o700) + link = work / "alias" + link.symlink_to(saved) + for path, expected, nonce in ((witness, sha, NONCE), (saved, "0" * 64, NONCE), + (saved, sha, "x" * 32), (script, digest(script), NONCE), + (partial, digest(partial), NONCE), (link, sha, NONCE), (work, sha, NONCE)): + result = subprocess.run(args(probe, path, expected, nonce), input=b"", capture_output=True, + timeout=5, cwd=work) + require(result.returncode == 126 and not result.stdout, f"unexpected admission of {path}: {result}") + with open(os.devnull, "rb") as wrong_control: + result = subprocess.run(args(probe, saved, sha), stdin=wrong_control, capture_output=True, + timeout=5, cwd=work) + require(result.returncode == 126 and not result.stdout, "ordinary file accepted as control") + print("Eight invalid image, identity and descriptor configurations refused") + + shutil.copyfile(ROOT / "tests/corpus/frontend/gcc-live.cpp", work / "input.cpp") + with subprocess.Popen(args(probe, compiler, digest(compiler), mode="observe"), stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=work) as child: + try: + out, err = child.communicate(timeout=45) + finally: + if child.poll() is None: + child.kill() + child.wait(timeout=3) + require(child.returncode == 0 and not err, f"real compiler exit {child.returncode}: {err!r}") + events = [json.loads(line) for line in out.splitlines()] + require(events and events[0]["kind"] == "hello" and events[0]["pid"] == child.pid + and events[0]["backend"] == "gcc-16.2.0/vls-eval-1", "compiler-origin handshake failed") + require(all(e["nonce"] == NONCE and e["seq"] == i for i, e in enumerate(events)), "invalid event stream") + values = [int(e["value"]["bitsHex"], 16) for e in events + if e["kind"] == "value" and e["value"]["kind"] == "integer"] + require(values == [17, 34, 22, 44] and events[-1]["kind"] == "frontendEnd", f"unexpected returns: {values}") + print("Real sealed cc1plus reported returns 17, 34, 22 and 44") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--probe", type=Path, required=True) + parser.add_argument("--cc1plus", type=Path, required=True) + parser.add_argument("--cc", default="cc") + cli = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="vls-gcc-leaf-") as folder: + verify_leaf(cli.probe.resolve(strict=True), cli.cc1plus.resolve(strict=True), cli.cc, Path(folder)) diff --git a/tests/native/GccSupervisor.py b/tests/native/GccSupervisor.py new file mode 100644 index 0000000..5bd3af7 --- /dev/null +++ b/tests/native/GccSupervisor.py @@ -0,0 +1,217 @@ +"""Exercise the private compiler supervisor, live controls, cleanup and offline replay.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import select +import shutil +import subprocess +import tempfile +import time + + +ROOT = Path(__file__).resolve().parents[2] +WITNESS = r""" +#include +#include +#include +#include +int main(void) { + char mode[32] = {0}; + FILE *file = fopen("input.cpp", "r"); + if (!file || fscanf(file, "%31s", mode) != 1) return 3; + fclose(file); + dprintf(4, "{\"v\":1,\"nonce\":\"%s\",\"seq\":0,\"kind\":\"hello\"," + "\"backend\":\"gcc-16.2.0/vls-eval-1\",\"pid\":%ld," + "\"capabilities\":[\"integralReturn\",\"cooperativeStep\"]," + "\"kinds\":[\"hello\",\"enter\",\"body\",\"value\",\"cached\",\"stopped\"," + "\"resumed\",\"leave\",\"terminal\",\"frontendEnd\"]}\n", + getenv("VLS_GCC_NONCE"), (long)getpid()); + if (!strcmp(mode, "partial")) { dprintf(4, "{\"v\":"); return 0; } + if (!strcmp(mode, "flood")) { + char block[4096]; memset(block, 'a', sizeof block); + for (int i=0; i<80; ++i) if (write(2, block, sizeof block) < 0) break; + return 0; + } + if (!strcmp(mode, "descendant")) { + pid_t sub = fork(); + if (sub < 0) return 2; + if (sub == 0) { sleep(20); _exit(0); } + dprintf(2, "descendant=%ld\n", (long)sub); + return 0; + } + if (!strcmp(mode, "running")) { sleep(20); return 0; } + return 2; +} +""" + + +def check(value, message): + if not value: + raise RuntimeError(message) + + +def digest(path): + with path.open("rb") as source: + return hashlib.file_digest(source, "sha256").hexdigest() + + +class Client: + def __init__(self, probe, compiler, sha, source, trace, step): + args = [probe, "run", compiler, sha, source, trace, *(["--step"] if step else [])] + self.process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, bufsize=0) + self.buffer = bytearray() + + def __enter__(self): + return self + + def __exit__(self, *unused): + if self.process.poll() is None: + self.process.terminate() + try: + self.process.wait(timeout=5) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait(timeout=3) + for pipe in (self.process.stdin, self.process.stdout, self.process.stderr): + pipe.close() + + def read(self, expected): + deadline = time.monotonic() + 18 + while b"\n" not in self.buffer: + left = deadline - time.monotonic() + check(left > 0 and select.select([self.process.stdout], [], [], left)[0], + f"timed out waiting for {expected}") + chunk = os.read(self.process.stdout.fileno(), 8192) + check(chunk, f"probe closed stdout before {expected}") + self.buffer.extend(chunk) + check(len(self.buffer) <= 73728, "oversized probe notice") + line, _, self.buffer = self.buffer.partition(b"\n") + data = json.loads(line) + check(data["kind"] == expected, f"expected {expected}, got {data!r}") + return data + + def send(self, control): + self.process.stdin.write((control + "\n").encode("ascii")) + + def finish(self, expected, code): + message = self.read("finished") + actual = self.process.wait(timeout=5) + check(message["outcome"] == expected and actual == code, f"unexpected completion: {actual}, {message}") + check(not self.buffer and not self.process.stdout.read(1), "trailing process output") + check(not self.process.stderr.read(8192), "unexpected supervisor stderr") + + +def replay(probe, trace, seq=None): + cmd = [probe, "replay", trace, *([str(seq)] if seq is not None else [])] + result = subprocess.run(cmd, capture_output=True, timeout=8, check=True) + check(not result.stderr, f"unexpected replay stderr {result.stderr!r}") + return json.loads(result.stdout) + + +def integral(snapshot): + frame = snapshot["frames"][-1] + value = frame["value"] + check(value["kind"] == "integer" and value["signed"] and value["precision"] == 32, + f"unexpected scalar {value}") + return frame["name"], int(value["bitsHex"], 16) + + +def stepped(probe, compiler, sha, source, trace, inner, outer, cancel=False): + with Client(probe, compiler, sha, source, trace, True) as client: + start = client.read("started") + nonce, pid = start["nonce"], start["pid"] + stop = client.read("stopped") + seq = stop["stop"] + check(nonce == stop["nonce"] and client.process.poll() is None, "invalid initial stop") + os.kill(pid, 0) + client.send(f"{nonce} {seq} inspect") + live = client.read("inspection")["snapshot"] + check(integral(live) == ("reflected_value", inner), "wrong live inner value") + check(live["stop"] == seq and not live["frontendEnded"], "incorrect live generation") + client.send(f"{'0'*32} {seq} step") + client.read("rejected") + client.send(f"{nonce} {seq + 1} continue") + client.read("rejected") + check(not select.select([client.process.stdout], [], [], .035)[0], "compiler advanced on stale controls") + if cancel: + client.send(f"{nonce} {seq} cancel") + client.finish("cancelled", 125) + view = replay(probe, trace) + check(view["partial"] and view["terminal"] == "cancelled" and integral(view)[1] == inner, + "cancel lost its verified prefix") + return [seq] + client.send(f"{nonce} {seq} step") + stepped_stop = client.read("stopped")["stop"] + check(stepped_stop > seq, "stop generation did not advance") + client.send(f"{nonce} {seq} step") + client.read("rejected") + client.send(f"{nonce} {stepped_stop} inspect") + check(integral(client.read("inspection")["snapshot"]) == ("twice", outer), "wrong live outer value") + client.send(f"{nonce} {stepped_stop} continue") + client.finish("completed", 0) + return [seq, stepped_stop] + + +def verify(probe, compiler, cc, work): + fixture = work / "user.cpp" + original = (ROOT / "tests/corpus/frontend/gcc-live.cpp").read_text() + selected = work / "private-cc1plus" + shutil.copy2(compiler, selected) + sha = digest(selected) + old, new, cancelled = (work / name for name in ("old.trace", "edited.trace", "cancelled.trace")) + fixture.write_text(original) + stops = stepped(probe, selected, sha, fixture, old, 17, 34) + fixture.write_text(original.replace("Ready = 17", "Ready = 41")) + stepped(probe, selected, sha, fixture, new, 41, 82) + stepped(probe, selected, sha, fixture, cancelled, 41, 82, cancel=True) + selected.unlink() + fixture.unlink() + for seq, value in zip(stops, (17, 34)): + view = replay(probe, old, seq) + check(view["sequence"] == seq and view["stop"] == seq and integral(view)[1] == value, + "offline replay disagrees with the old live value") + check(view["source"] == original and view["compilerSha256"] == sha and view["outcome"] == "completed", + "offline identity or completion differs") + print("Live and offline GCC sessions agree on 17/34 and 41/82, stale controls and cancellation") + + incomplete = work / "partial.trace" + incomplete.write_bytes(old.read_bytes()[:-5]) + view = replay(probe, incomplete, stops[0]) + check(view["partial"] and view["outcome"] is None and integral(view)[1] == 17, "incomplete tail promoted") + witness_c, witness = work / "witness.c", work / "witness" + witness_c.write_text(WITNESS) + subprocess.run([cc, witness_c, "-o", witness], check=True, timeout=30) + witness_sha = digest(witness) + for mode in ("partial", "flood", "descendant", "running"): + fixture.write_text(mode) + journal = work / f"{mode}.vls" + with Client(probe, witness, witness_sha, fixture, journal, mode == "running") as client: + started = client.read("started") + if mode == "running": + client.send(started["nonce"] + " cancel") + client.finish("cancelled", 125) + else: + client.finish("truncated", 126) + state = replay(probe, journal) + check(state["partial"], f"incomplete witness {mode} declared complete") + if mode == "descendant": + pid = int(re.search(r"descendant=(\d+)", state["diagnostics"]).group(1)) + check(not Path(f"/proc/{pid}").exists(), "adopted descendant was not reaped") + if mode == "flood": + check(0 < len(state["diagnostics"]) <= 256*1024, "diagnostics escaped the capture limit") + print("Verified truncated input, bounded stderr, running cancellation and leader-first process cleanup") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--probe", type=Path, required=True) + parser.add_argument("--cc1plus", type=Path, required=True) + parser.add_argument("--cc", default="cc") + opts = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="vls-gcc-supervisor-") as directory: + verify(opts.probe.resolve(strict=True), opts.cc1plus.resolve(strict=True), opts.cc, Path(directory)) diff --git a/tests/native/InstalledServer.py b/tests/native/InstalledServer.py new file mode 100644 index 0000000..146d727 --- /dev/null +++ b/tests/native/InstalledServer.py @@ -0,0 +1,122 @@ +"""Run a staged VLS from an empty directory without a tool search path.""" + +import argparse +import json +from pathlib import Path +import subprocess +import tempfile + + +def frame(message): + payload = json.dumps({"jsonrpc": "2.0", **message}, ensure_ascii=False).encode() + return f"Content-Length: {len(payload)}\r\n\r\n".encode() + payload + + +def replies(data): + result = [] + while data: + header, data = data.split(b"\r\n\r\n", 1) + if not header.startswith(b"Content-Length: "): + raise ValueError(f"unexpected stdout header {header!r}") + length = int(header.removeprefix(b"Content-Length: ")) + if not 0 < length <= len(data): + raise ValueError("truncated LSP response") + result.append(json.loads(data[:length])) + data = data[length:] + return result + + +def check_install(binary, work, encoding): + def start(args, data=b""): + return subprocess.run([binary, *args], cwd=work, input=data, capture_output=True, + check=True, timeout=10, env={"LC_ALL": "C", "PATH": ""}) + + version = start(["--version"]) + if version.stdout != b"VoidLanguageServer 0.1.0\n" or version.stderr: + raise ValueError("unexpected version output") + document = {"uri": "untitled:installed-server"} + + def edit(version, left, right, text): + return {"method": "textDocument/didChange", "params": { + "textDocument": {**document, "version": version}, "contentChanges": [{ + "range": {"start": {"line": 0, "character": left}, + "end": {"line": 0, "character": right}}, "text": text}]}} + + messages = [ + {"method": "initialize", "id": 1, "params": {"capabilities": { + "general": {"positionEncodings": [encoding]}}}}, + {"method": "initialized", "params": {}}, + {"method": "textDocument/didOpen", "params": {"textDocument": { + **document, "version": 1, "languageId": "cpp", "text": "a"}}}, + edit(2, 0, 1, "😀"), + edit(3, 1, 1, "b"), + {"method": "textDocument/didClose", "params": {"textDocument": document}}, + {"method": "shutdown", "id": 2}, + {"method": "exit"}, + ] + process = start(["--stdio"], b"".join(map(frame, messages))) + responses = replies(process.stdout) + if [r["id"] for r in responses] != [1, 2] or responses[1]["result"] is not None: + raise ValueError(f"unexpected replies: {responses}") + capabilities = responses[0]["result"]["capabilities"] + if capabilities["positionEncoding"] != encoding or capabilities["textDocumentSync"]["change"] != 2: + raise ValueError(f"unexpected initialization: {capabilities}") + witness = "splits a Unicode scalar" if encoding == "utf-8" else "splits a surrogate pair" + if process.stderr.count(b"\n") != 1 or witness.encode() not in process.stderr: + raise ValueError(f"edit did not observe the preceding replacement: {process.stderr!r}") + print(f"{encoding}: installed binary negotiated sync, applied the edit and detected the split") + + +def check_provider(binary, work, root, database, provider, document): + rows = json.loads(database.read_bytes()) + owners = sum((database.parent / row["directory"] / row["file"]).resolve() == document for row in rows) + if not owners: + raise ValueError(f"{database} has no command for {document}") + args = [str(binary), "--stdio"] + if provider == "compdb": + args += ["--workspace-root", str(root), "--provider", "compdb", "--compdb", str(database)] + messages = [ + {"method": "initialize", "id": 1, "params": {"capabilities": {}, "workspaceFolders": [ + {"uri": root.as_uri(), "name": root.name}]}}, + {"method": "initialized", "params": {}}, + {"method": "voidLanguageServer/providerStatus", "id": 2, "params": { + "workspaceUri": root.as_uri(), "textDocument": {"uri": document.as_uri()}}}, + {"method": "shutdown", "id": 3}, + {"method": "exit"}, + ] + process = subprocess.run(args, cwd=work, input=b"".join(map(frame, messages)), + capture_output=True, check=True, timeout=15, env={"LC_ALL": "C", "PATH": ""}) + records = replies(process.stdout) + if process.stderr or [r["id"] for r in records] != [1, 2, 3]: + raise ValueError(f"unexpected provider transcript: {process.stderr!r}, {records!r}") + status = records[1]["result"] + if (status["provider"], status["state"], status["workspaceUri"]) != (provider, "ready", root.as_uri()): + raise ValueError(f"provider not ready: {status!r}") + if (status["contextCount"] != len(rows) or len(status["alternatives"]) != min(owners, 16) or + status.get("alternativesTruncated", False) != (owners > 16) or + status["selected"]["owningTu"] != document.as_uri()): + raise ValueError(f"provider disagrees with {database}: {status!r}") + if provider == "vbs" and status["nativeGeneration"] != database.parent.name: + raise ValueError(f"selected VBS generation changed: {status!r}") + print(f"{provider}: installed server reported {len(rows)} commands for {root.name}, {owners} for {document.name}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("executable", type=Path) + parser.add_argument("--workspace", type=Path, help="workspace used to build the installed server") + parser.add_argument("--vbs-database", type=Path, help="expected selected immutable VBS generation database") + parser.add_argument("--compdb", type=Path, help="comparison build's compilation database") + parser.add_argument("--document", type=Path, default=Path("src/main.cpp"), help="translation unit under the workspace") + args = parser.parse_args() + if any((args.workspace, args.vbs_database, args.compdb)) and not all((args.workspace, args.vbs_database, args.compdb)): + parser.error("--workspace, --vbs-database and --compdb must be supplied together") + binary = args.executable.resolve(strict=True) + with tempfile.TemporaryDirectory(prefix="vls-install-check-") as work: + for encoding in ("utf-8", "utf-16"): + check_install(binary, work, encoding) + if args.workspace: + root = args.workspace.resolve(strict=True) + document = (root / args.document).resolve(strict=True) + for provider, db in (("vbs", args.vbs_database), ("compdb", args.compdb)): + check_provider(binary, work, root, db.resolve(strict=True), provider, document) diff --git a/tests/native/LiveDap.py b/tests/native/LiveDap.py new file mode 100644 index 0000000..23b03c1 --- /dev/null +++ b/tests/native/LiveDap.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Drive vls-dap --live against the scripted worker: control, inspection, stale rejects.""" + +import argparse +import json +import os +from pathlib import Path +import select +import subprocess +import tempfile +import time + + +def check(condition, detail): + if not condition: + raise ValueError(detail) + + +class Adapter: + def __init__(self, argv): + self.process = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, env={**os.environ, "LC_ALL": "C"}) + self.sequence = 0 + self.buffer = b"" + + def send(self, message): + payload = json.dumps(message).encode() + self.process.stdin.write(f"Content-Length: {len(payload)}\r\n\r\n".encode() + payload) + self.process.stdin.flush() + + def send_request(self, command, arguments=None): + self.sequence += 1 + self.send({"seq": self.sequence, "type": "request", "command": command, + "arguments": arguments or {}}) + return self.sequence + + def request(self, command, arguments=None, timeout=15): + sequence = self.send_request(command, arguments) + while True: + message = self.read(timeout) + if message.get("type") == "response" and message.get("request_seq") == sequence: + return message + + def event(self, name, timeout=15): + deadline = time.monotonic() + timeout + while True: + remaining = deadline - time.monotonic() + check(remaining > 0, f"timed out waiting for the {name} event") + message = self.read(remaining) + if message.get("type") == "event" and message.get("event") == name: + return message + + def read(self, timeout): + while b"\r\n\r\n" not in self.buffer: + ready, _, _ = select.select([self.process.stdout], [], [], timeout) + check(ready, "DAP response deadline expired") + chunk = os.read(self.process.stdout.fileno(), 65536) + check(chunk, "the adapter closed stdout") + self.buffer += chunk + header, rest = self.buffer.split(b"\r\n\r\n", 1) + length = int(header.removeprefix(b"Content-Length: ")) + while len(rest) < length: + chunk = os.read(self.process.stdout.fileno(), 65536) + check(chunk, "truncated DAP response") + rest += chunk + body, self.buffer = rest[:length], rest[length:] + return json.loads(body) + + def close(self): + try: + self.request("disconnect") + except (OSError, ValueError, TimeoutError): + pass + try: + self.process.stdin.close() + except OSError: + pass + try: + self.process.wait(timeout=10) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + + +def run(adapter, worker): + with tempfile.TemporaryDirectory(prefix="vls-live-dap-") as temp: + root = Path(temp) + source = root / "normal.cpp" + source.write_text("int value = 17;\n", encoding="utf-8") + trace = root / "session.vls" + client = Adapter([str(adapter), "--live", str(worker), "/private/cc1plus", + "a" * 64, str(source), str(trace)]) + try: + initialized = client.request("initialize", {"adapterID": "vls"}) + check(initialized["success"], initialized) + client.event("initialized") + client.send_request("launch", {}) + client.request("configurationDone", {}) + stopped = client.event("stopped") + check(stopped["body"]["threadId"] == 1, stopped) + + threads = client.request("threads") + check(len(threads["body"]["threads"]) == 1, threads) + stack = client.request("stackTrace", {"threadId": 1}) + check("body" in stack, stack) + frame = stack["body"]["stackFrames"][0] + check(frame["name"] == "fixture_frame" and frame["line"] == 1, frame) + scopes = client.request("scopes", {"frameId": frame["id"]}) + reference = scopes["body"]["scopes"][0]["variablesReference"] + variables = client.request("variables", {"variablesReference": reference}) + names = {variable["name"]: variable["value"] for variable in variables["body"]["variables"]} + check(names.get("source") == "input.cpp" and names.get("depth") == "0", + f"unexpected live variables: {names}") + check(names.get("Result") == "17", f"typed value was not projected: {names}") + + breakpoints = client.request("setBreakpoints", + {"source": {"path": "input.cpp"}, "lines": [2, 99]}) + check(breakpoints["success"] and + len(breakpoints["body"]["breakpoints"]) == 2, breakpoints) + moved = client.request("next") + check(moved["success"], moved) + stopped_event = client.event("stopped") + check(stopped_event["body"].get("hitBreakpointIds") == [2], stopped_event) + stale = client.request("scopes", {"frameId": frame["id"]}) + check(stale["success"] is False and "stale" in stale["message"], stale) + stack = client.request("stackTrace", {"threadId": 1}) + check(stack["body"]["stackFrames"][0]["line"] == 2, stack) + + paused = client.request("pause") + check(paused["success"] is False, paused) + finished = client.request("continue") + check(finished["success"], finished) + client.event("terminated") + finally: + client.close() + print("live DAP passed: stopped/typed inspection/breakpoints/step/stale rejection/continue, pause refused") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--adapter", required=True, type=Path) + parser.add_argument("--worker", required=True, type=Path) + options = parser.parse_args() + run(options.adapter.resolve(strict=True), options.worker.resolve(strict=True)) + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, subprocess.SubprocessError) as exc: + raise SystemExit(f"verify-live-dap: {exc}") diff --git a/tests/native/NeovimClient.lua b/tests/native/NeovimClient.lua new file mode 100644 index 0000000..bc55b88 --- /dev/null +++ b/tests/native/NeovimClient.lua @@ -0,0 +1,109 @@ +-- Run with nvim --headless -u NONE -i NONE -l tests/native/NeovimClient.lua. +local server = assert(vim.env.VLS_SERVER, "set VLS_SERVER to the installed vls") +local adapter = assert(vim.env.VLS_DAP, "set VLS_DAP to the installed vls-dap") +local trace = assert(vim.env.VLS_TRACE, "set VLS_TRACE to integral-17.vls") +local plugin = assert(vim.env.VLS_NVIM_DAP, "set VLS_NVIM_DAP to the nvim-dap checkout") +local repository = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h:h:h") +vim.opt.runtimepath:prepend(plugin) +vim.opt.runtimepath:prepend(repository .. "/clients/neovim") + +local vls = require("vls") +vls.setup({ server = server, dap_adapter = adapter }) +dofile(repository .. "/clients/neovim/plugin/vls.lua") +local dap = require("dap") + +local function wait_for(label, predicate, timeout) + assert(vim.wait(timeout or 10000, predicate, 25), "timed out waiting for " .. label) +end + +local work = vim.fn.tempname() +assert(vim.fn.mkdir(work, "p") == 1) +local file = work .. "/unit.cpp" +assert(vim.fn.writefile({ "int value = 17;", "int read() { return value; }" }, file) == 0) +vim.cmd.edit(vim.fn.fnameescape(file)) +local buffer = vim.api.nvim_get_current_buf() +vim.bo[buffer].filetype = "cpp" + +local client, err = vls.start(buffer) +assert(client, err) +wait_for("LSP initialization", function() return client.initialized end) + +local status, status_err = vls.status(buffer) +assert(not status_err and type(status.state) == "string", vim.inspect({ status, status_err })) +local analysis, analysis_err = vls.analysis_status(buffer) +assert(not analysis_err and type(analysis.state) == "string", + vim.inspect({ analysis, analysis_err })) + +local messages = {} +local original_notify = vim.notify +vim.notify = function(message) table.insert(messages, message) end +vim.cmd("VlsStatus") +vim.notify = original_notify +wait_for("status notification", function() return #messages > 0 end) +assert(messages[1]:find("VoidLanguageServer provider status", 1, true), messages[1]) + +local stops = 0 +dap.listeners.after.event_stopped.vls_client_test = function(_, event) + assert(event.threadId == 1) + stops = stops + 1 +end +local replay, replay_err = vls.replay(trace) +assert(replay, replay_err) +wait_for("first replay stop", function() return stops == 1 and dap.session() ~= nil end) +local session = assert(dap.session()) + +local function request(method, arguments) + local done, failure, body = false, nil, nil + session:request(method, arguments, function(problem, result) + failure, body, done = problem, result, true + end) + wait_for(method, function() return done end) + assert(not failure, vim.inspect(failure)) + return body +end + +local function read_value() + local frame = assert(request("stackTrace", { threadId = 1 }).stackFrames[1]) + local scope = request("scopes", { frameId = frame.id }).scopes[1] + local variables = request("variables", { variablesReference = scope.variablesReference }) + for _, variable in ipairs(variables.variables) do + if variable.name == "Result" then + return variable.value, frame.name + end + end + error("recorded result is missing") +end + +local value, name = read_value() +assert(value == "17" and name == "reflected_value", vim.inspect({ value, name })) +local first = assert(vls.session()) +assert(type(first.sessionId) == "string" and type(first.generation) == "number") +local page = assert(vls.timeline(0, 4)) +assert(page.sessionId == first.sessionId and #page.events > 0, vim.inspect(page)) +local source = assert(vls.source()) +assert(vim.fn.sha256(source) == first.sourceSha256) + +dap.continue() +wait_for("second replay stop", function() return stops == 2 and session.stopped_thread_id == 1 end) +value, name = read_value() +assert(value == "34" and name == "twice", vim.inspect({ value, name })) +local stale, stale_err = vls.timeline() +assert(not stale and stale_err and stale_err:find("stale", 1, true), + vim.inspect({ stale, stale_err })) +local second = assert(vls.session()) +assert(second.generation > first.generation) +local page2 = assert(vls.timeline(0, 2)) +assert(page2.generation == second.generation) +vim.cmd("VlsTimeline 0 2") +local view = vim.api.nvim_get_current_buf() +local lines = vim.api.nvim_buf_get_lines(view, 0, -1, false) +assert(lines[1] and lines[1]:find("session", 1, true), vim.inspect(lines)) +vim.cmd("close") + +vls.stop() +wait_for("replay shutdown", function() return dap.session() == nil end) +client:stop() +wait_for("server shutdown", function() + return #vim.lsp.get_clients({ name = "VoidLanguageServer" }) == 0 +end) +print("Neovim client passed: LSP status, replay session, timeline, source and stale rejection") diff --git a/tests/native/NeovimDiagnostics.lua b/tests/native/NeovimDiagnostics.lua new file mode 100644 index 0000000..c8f5cee --- /dev/null +++ b/tests/native/NeovimDiagnostics.lua @@ -0,0 +1,56 @@ +-- Exercise a real unsaved edit through the built-in Neovim LSP client. +local server = assert(vim.env.VLS_SERVER, "set VLS_SERVER to the installed vls") +local profile_path = assert(vim.env.VLS_GCC_PROFILE, "set VLS_GCC_PROFILE to the prepared stock GCC profile") +local profile = vim.json.decode(table.concat(vim.fn.readfile(profile_path), "\n")) +local root = vim.fn.tempname() +assert(vim.fn.mkdir(root) == 1) +local file = root .. "/unit.cpp" +local client + +local function wait_for(label, predicate) + assert(vim.wait(15000, predicate, 25), "timed out waiting for " .. label) +end + +local function run() + local original = "int read() { return value; }" + assert(vim.fn.writefile({ "int value = 17;", original }, file) == 0) + local row = { file = file, directory = root, + arguments = { profile.driver.path, "-std=c++26", "-freflection", "-c", file } } + assert(vim.fn.writefile({ vim.json.encode({ row }) }, root .. "/compile_commands.json") == 0) + vim.cmd.edit(vim.fn.fnameescape(file)) + local buf = vim.api.nvim_get_current_buf() + vim.bo[buf].filetype = "cpp" + local id = assert(vim.lsp.start({ + name = "VoidLanguageServer", + cmd = { server, "--stdio", "--workspace-root", root, "--provider", "compdb", "--gcc-profile", profile_path }, + root_dir = root, + flags = { debounce_text_changes = 10 }, + }, { bufnr = buf })) + client = assert(vim.lsp.get_client_by_id(id)) + wait_for("initialization", function() return client.initialized end) + local params = { textDocument = { uri = vim.uri_from_bufnr(buf) }, workspaceUri = vim.uri_from_fname(root) } + local reply = assert(client:request_sync("voidLanguageServer/providerStatus", params, 5000, buf)) + assert(not reply.err and reply.result.state == "ready" and reply.result.contextCount == 1, + vim.inspect(reply)) + assert(reply.result.selected.owningTu == params.textDocument.uri) + local start = assert(original:find("value", 1, true)) - 1 + vim.api.nvim_buf_set_text(buf, 1, start, 1, start + 5, { "missing" }) + wait_for("stock compiler diagnosis", function() + for _, d in ipairs(vim.diagnostic.get(buf)) do + if d.source == "gcc" and d.message:find("missing", 1, true) and d.lnum == 1 + and d.col == start and d.end_col == start + 7 then return true end + end + end) + vim.api.nvim_buf_set_text(buf, 1, start, 1, start + 7, { "value" }) + wait_for("diagnostic clear", function() return #vim.diagnostic.get(buf) == 0 end) + assert(vim.fn.readfile(file)[2] == original) +end + +local ok, err = xpcall(run, debug.traceback) +if client then + client:stop() + if not vim.wait(5000, function() return client:is_stopped() end) then client:stop(true) end +end +vim.fn.delete(root, "rf") +assert(ok, err) +print("Neovim LSP passed: selected compile command, seven-byte stock GCC diagnostic and clear") diff --git a/tests/native/NeovimRename.lua b/tests/native/NeovimRename.lua new file mode 100644 index 0000000..bc11520 --- /dev/null +++ b/tests/native/NeovimRename.lua @@ -0,0 +1,85 @@ +-- Run with nvim --headless -u NONE -i NONE -l tests/native/NeovimRename.lua. +local repository = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h:h:h") +vim.opt.runtimepath:prepend(repository .. "/clients/neovim") +local vls = require("vls") + +local root = vim.fn.tempname() +vim.fn.mkdir(root .. "/left", "p") +vim.fn.mkdir(root .. "/right", "p") +local left = root .. "/left/unit.cpp" +local right = root .. "/right/header.hpp" +vim.fn.writefile({ "int value = 17;", "int read() { return value; }" }, left) +vim.fn.writefile({ "int value = 3;" }, right) + +local function load(path) + vim.cmd.edit(vim.fn.fnameescape(path)) + return vim.api.nvim_get_current_buf() +end +local left_buffer = load(left) +local right_buffer = load(right) + +local function snapshot(buffer) + return table.concat(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), "\n") +end + +local function edit(buffer, line, spelling, replacement) + local text = vim.api.nvim_buf_get_lines(buffer, line, line + 1, false)[1] + local start = assert(text:find(spelling, 1, true)) - 1 + return { range = { start = { line = line, character = start }, + ["end"] = { line = line, character = start + #spelling } }, + newText = replacement } +end + +local function changes() + return { + [vim.uri_from_bufnr(left_buffer)] = { + edit(left_buffer, 0, "value", "count"), + edit(left_buffer, 1, "value", "count"), + }, + [vim.uri_from_bufnr(right_buffer)] = { + edit(right_buffer, 0, "value", "count"), + }, + } +end + +local before_left, before_right = snapshot(left_buffer), snapshot(right_buffer) +assert(vls.apply_workspace_edit(changes())) +assert(snapshot(left_buffer):find("count", 1, true)) +assert(snapshot(right_buffer):find("count", 1, true)) + +vim.api.nvim_buf_set_lines(left_buffer, 0, -1, false, + { "int value = 17;", "int read() { return value; }" }) +vim.api.nvim_buf_set_lines(right_buffer, 0, -1, false, { "int value = 3;" }) +vim.bo[left_buffer].modified = false +vim.bo[right_buffer].modified = false +assert(snapshot(left_buffer) == before_left and snapshot(right_buffer) == before_right) + +-- Inject a failure in the second buffer write and require a full rollback. +local original = vim.api.nvim_buf_set_text +local calls = 0 +vim.api.nvim_buf_set_text = function(...) + calls = calls + 1 + if calls == 2 then + error("injected buffer failure") + end + return original(...) +end +local ok, err = vls.apply_workspace_edit(changes()) +vim.api.nvim_buf_set_text = original +assert(not ok and err:find("injected", 1, true), vim.inspect({ ok, err })) +assert(snapshot(left_buffer) == before_left and snapshot(right_buffer) == before_right) +assert(not vim.bo[left_buffer].modified and not vim.bo[right_buffer].modified) + +-- An invalid range is rejected before any buffer is touched. +local invalid = changes() +invalid[vim.uri_from_bufnr(right_buffer)][1].range.start.line = 99 +assert(not vls.apply_workspace_edit(invalid)) +assert(snapshot(left_buffer) == before_left and snapshot(right_buffer) == before_right) + +-- A read-only buffer refuses the whole transaction. +vim.bo[right_buffer].modifiable = false +assert(not vls.apply_workspace_edit(changes())) +vim.bo[right_buffer].modifiable = true +assert(snapshot(left_buffer) == before_left and snapshot(right_buffer) == before_right) + +print("Neovim rename passed: atomic apply, injected-failure rollback, invalid range and read-only refusal") diff --git a/tests/native/NeovimReplay.lua b/tests/native/NeovimReplay.lua new file mode 100644 index 0000000..b7854a7 --- /dev/null +++ b/tests/native/NeovimReplay.lua @@ -0,0 +1,68 @@ +-- Run with nvim --headless -u NONE -i NONE -l tests/native/NeovimReplay.lua. +local plugin = assert(vim.env.VLS_NVIM_DAP, "set VLS_NVIM_DAP to the nvim-dap checkout") +local adapter = assert(vim.env.VLS_DAP, "set VLS_DAP to the adapter executable") +local trace = assert(vim.env.VLS_TRACE, "set VLS_TRACE to integral-17.vls") +vim.opt.runtimepath:prepend(plugin) +local dap = require("dap") + +dap.adapters.vls = { type = "executable", command = adapter, args = { "--replay", trace } } +local stops = 0 +dap.listeners.after.event_stopped.vls_test = function(_, event) + assert(event.threadId == 1) + stops = stops + 1 +end + +local function wait_for(label, predicate) + assert(vim.wait(5000, predicate, 10), "timed out waiting for " .. label) +end + +local function request(session, method, args) + local done, err, body = false, nil, nil + session:request(method, args, function(problem, result) + err, body, done = problem, result, true + end) + wait_for(method, function() return done end) + assert(not err, vim.inspect(err)) + return body +end + +local function read_value(session) + local stack = request(session, "stackTrace", { threadId = 1 }) + local frame = assert(stack.stackFrames[1]) + assert(not frame.source and frame.line == 0) + local scope = request(session, "scopes", { frameId = frame.id }).scopes[1] + local reply = request(session, "variables", { variablesReference = scope.variablesReference }) + for _, var in ipairs(reply.variables) do + if var.name == "Result" then return var.value, frame.name end + end + error("recorded result is missing") +end + +dap.run({ type = "vls", name = "C++ constant evaluation", request = "launch" }) +wait_for("first stop", function() + return stops == 1 and dap.session() and dap.session().stopped_thread_id == 1 +end) +local session = assert(dap.session()) +local value, name = read_value(session) +assert(value == "17" and name == "reflected_value") +local first = request(session, "vls/session") +local query = { schemaVersion = first.schemaVersion, sessionId = first.sessionId, + generation = first.generation, start = 5, count = 4 } +local page = request(session, "vls/timeline", query) +assert(page.events[3].acknowledgedAction == "step" and page.events[3].acknowledgedStop == 6) +local source = request(session, "source", { sourceReference = first.sourceReference }) +assert(vim.fn.sha256(source.content) == first.sourceSha256) +dap.continue() +wait_for("outer return", function() return stops == 2 and session.stopped_thread_id == 1 end) +value, name = read_value(session) +assert(value == "34" and name == "twice") +local second = request(session, "vls/session") +assert(second.sessionId == first.sessionId and second.eventSequence == 10) +assert(second.generation > first.generation) +local disconnected = false +session:disconnect({}, function(err) + assert(not err, vim.inspect(err)) + disconnected = true +end) +wait_for("disconnect", function() return disconnected and dap.session() == nil end) +print("Neovim replay passed: reflected_value=17, twice=34, captured source and acknowledged timeline") diff --git a/tests/native/Preparation.py b/tests/native/Preparation.py new file mode 100644 index 0000000..bf2e350 --- /dev/null +++ b/tests/native/Preparation.py @@ -0,0 +1,273 @@ +"""Exercise tools/prepare-voidlibrary with Git and source stores owned by the fixture.""" + +from concurrent.futures import ThreadPoolExecutor, wait +import hashlib +import json +import os +from pathlib import Path +import runpy +import shlex +import shutil +import signal +import stat +import subprocess +import tempfile +import time +import unittest +from unittest.mock import patch + + +TOOL = Path(__file__).resolve().parents[2] / "tools/prepare-voidlibrary" +HEADERS = """ +Async/Task Configuration/Argparse Core/Hash Crypto/Crypto Data/StrictJson Functional/Result +Math/Numeric System/Process Testing/Test Testing/Detail/Registry Text/Url Time/Clock Unicode/Utf +Detail/Enum Log/Log Stacktrace/Color +""".split() +SOURCES = "Configuration/Argparse Crypto/Crypto LogState/State System/Process Testing/Main".split() +INCLUDED = ({f"include/Void/{name}.hpp" for name in HEADERS} | + {f"src/{name}.cpp" for name in SOURCES} | {"src/Crypto/BuiltinHash.hpp"}) +EXCLUDED = { + ".gitattributes", "src/Core/module.cmake", "include/Void/Core/.private.hpp", + "include/Void/Other/Header.hpp", "include/Void/System/AsyncProcess.hpp", "README.md", +} +JSON_HEADER = "include/Void/Data/StrictJson.hpp" + + +class PreparationTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.tool = self.root / "project/tools/prepare-voidlibrary" + self.tool.parent.mkdir(parents=True) + shutil.copy2(TOOL, self.tool) + self.store = self.tool.parents[1] / "build/voidlibrary" + self.current = self.store / "current" + self.source = self.root / "checkout" + self.source.mkdir() + self.env = {k: v for k, v in os.environ.items() + if not k.startswith("GIT_") and k != "VLS_VOID_SOURCE_DIR"} + self.env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) + self.git("init", "--quiet", "--template=") + for name in INCLUDED | EXCLUDED: + self.write(name, f"// {name}\n") + self.write(".gitattributes", "*.hpp filter=fixture\n") + self.git("add", "--", *sorted(INCLUDED | EXCLUDED)) + self.git("commit", "-qm", "synthetic recipe inputs") + self.revision = self.git("rev-parse", "HEAD").strip() + + def git(self, *args): + return subprocess.check_output( + ["git", "-c", "core.hooksPath=/dev/null", "-c", "user.name=Fixture", + "-c", "user.email=fixture@invalid", "-C", self.source, *args], + text=True, env=self.env, + ) + + def write(self, path, data): + dest = self.source / path + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_text(data, encoding="utf-8") + + def cli(self, *args, env=None): + return subprocess.run([self.tool, *args], env=self.env | (env or {}), capture_output=True, + text=True, timeout=30) + + def prepare(self, source=None): + result = self.cli("--source", source or self.source) + self.assertEqual(result.returncode, 0, result.stderr) + return Path(result.stdout.strip()) + + def failed_update(self, target): + result = self.cli("--source", self.source) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.current.resolve(strict=True), target) + return result.stderr + + def check_generation(self, target): + metadata = (target / "provenance.json").read_bytes() + self.assertEqual(target.name, hashlib.sha256(metadata).hexdigest()) + self.assertEqual(target.parent, self.store / "sources") + self.assertLessEqual(len(metadata), 32768) + self.assertTrue((target / "src/Core").is_dir()) + self.assertFalse(os.path.lexists(target / "build.cpp")) + return json.loads(metadata) + + def test_allowlist_provenance_and_duplicate(self): + self.git("config", "filter.fixture.clean", "false") + self.git("config", "filter.fixture.smudge", "false") + self.git("config", "filter.fixture.required", "true") + self.write("src/System/Untracked.cpp", "untracked canary") + self.write("build.cpp", "untracked descriptor") + index = self.source / ".git/index" + before = (index.stat().st_mtime_ns, index.read_bytes()) + target = self.prepare() + self.assertEqual(os.readlink(self.current), f"sources/{target.name}") + info = self.check_generation(target) + self.assertEqual(info["source_kind"], "local") + self.assertEqual(info["source_path"], str(self.source)) + self.assertEqual(info["revision"], self.revision) + self.assertFalse(info["dirty"]) + files = {p.relative_to(target).as_posix() for p in target.rglob("*") if p.is_file()} + self.assertEqual(files, INCLUDED | {"provenance.json"}) + digest = hashlib.sha256() + for name in sorted(INCLUDED): + entry = target / name + self.assertEqual(stat.S_IMODE(entry.stat().st_mode), 0o444) + digest.update(name.encode() + b"\0" + hashlib.sha256(entry.read_bytes()).digest()) + self.assertEqual(digest.hexdigest(), info["content_sha256"]) + self.assertEqual(stat.S_IMODE(target.stat().st_mode), 0o555) + again = self.cli(env={"VLS_VOID_SOURCE_DIR": str(self.source)}) + self.assertEqual(again.returncode, 0, again.stderr) + self.assertEqual(Path(again.stdout.strip()), target) + self.write(JSON_HEADER, "raw edited header with rejecting Git filters") + self.assertTrue(self.check_generation(self.prepare())["dirty"]) + self.assertEqual((index.stat().st_mtime_ns, index.read_bytes()), before) + + def test_dirty_sources_staged_additions_and_prior_build(self): + previous = self.prepare().resolve(strict=True) + old_data = (previous / JSON_HEADER).read_bytes() + self.write(JSON_HEADER, "// tracked local edit\n") + self.write("src/System/Platform/Extension.cpp", "// staged local source\n") + self.git("add", "--", "src/System/Platform/Extension.cpp") + target = self.prepare() + info = self.check_generation(target) + self.assertTrue(info["dirty"]) + self.assertEqual(info["revision"], self.revision) + self.assertNotEqual(info["content_sha256"], self.check_generation(previous)["content_sha256"]) + self.assertEqual((target / JSON_HEADER).read_text(), "// tracked local edit\n") + self.assertTrue((target / "src/System/Platform/Extension.cpp").is_file()) + self.assertFalse((previous / "src/System/Platform/Extension.cpp").exists()) + self.assertEqual((previous / JSON_HEADER).read_bytes(), old_data) + + def test_unsupported_tracked_translation_unit_preserves_previous_generation(self): + previous = self.prepare() + name = "src/System/Window Helpers.cpp" + self.write(name, "// valid source with an unsupported spelling\n") + self.git("add", "--", name) + self.assertIn("unsupported tracked translation unit", self.failed_update(previous)) + + def test_descriptor_rejected_in_index_and_head(self): + previous = self.prepare() + self.write("build.cpp", "synthetic descriptor") + self.git("add", "--", "build.cpp") + self.assertIn("tracked root build.cpp", self.failed_update(previous)) + self.git("commit", "-qm", "synthetic descriptor") + self.git("rm", "-q", "--", "build.cpp") + self.assertIn("tracked root build.cpp", self.failed_update(previous)) + + def test_rejects_links_missing_inputs_and_unstable_capture(self): + previous = self.prepare() + data = self.source / "include/Void/Data" + moved = self.root / "moved" + data.rename(moved) + data.symlink_to(moved, target_is_directory=True) + self.failed_update(previous) + data.unlink() + moved.rename(data) + leaf = self.source / JSON_HEADER + leaf.unlink() + self.failed_update(previous) + leaf.symlink_to(self.root / "absent") + self.failed_update(previous) + self.git("add", "--", JSON_HEADER) + self.assertIn("link", self.failed_update(previous)) + leaf.unlink() + self.write(JSON_HEADER, "regular again") + self.git("update-index", "--cacheinfo", f"160000,{self.revision},{JSON_HEADER}") + self.assertIn("link", self.failed_update(previous)) + oid = self.git("rev-parse", "HEAD:" + JSON_HEADER).strip() + self.git("update-index", "--cacheinfo", f"100644,{oid},{JSON_HEADER}") + + mod = runpy.run_path(str(self.tool)) + read_local = mod["local_file"] + + def changing_file(root, path): + result = read_local(root, path) + if path == JSON_HEADER and result[0] == b"regular again": + self.write(path, "changed after the first read") + return result + + with patch.dict(mod["prepare"].__globals__, local_file=changing_file): + with self.assertRaisesRegex(mod["PreparationError"], "changed during preparation"): + mod["prepare"](self.source) + self.assertEqual(self.current.resolve(strict=True), previous) + + def test_concurrent_publications_and_failed_fetch(self): + first = self.prepare() + second_source = self.root / "second-checkout" + shutil.copytree(self.source, second_source) + (second_source / JSON_HEADER).write_text("second source") + with ThreadPoolExecutor(max_workers=4) as pool: + pending = [pool.submit(self.prepare, src) for src in [self.source, second_source] * 4] + while True: + self.check_generation(self.current.resolve(strict=True)) + if not wait(pending, timeout=0.005).not_done: + break + targets = {future.result() for future in pending} + self.assertEqual(len(targets), 2) + self.assertEqual(set((self.store / "sources").iterdir()), targets) + self.assertIn(first, targets) + + previous = self.current.resolve(strict=True) + trap = self.root / "offline" + trap.mkdir() + shim = trap / "git" + shim.write_text("#!/bin/sh\nfor arg do\n if [ \"$arg\" = fetch ]; then\n" + " echo synthetic-fetch-diagnostic >&2\n exit 76\n fi\ndone\n" + f"exec {shlex.quote(shutil.which('git'))} \"$@\"\n") + shim.chmod(0o755) + result = self.cli(env={"PATH": f"{trap}:{self.env['PATH']}"}) + self.assertNotEqual(result.returncode, 0) + self.assertIn("git fetch failed (exit 76)", result.stderr) + self.assertNotIn("synthetic-fetch-diagnostic", result.stderr) + self.assertEqual(self.current.resolve(strict=True), previous) + self.check_generation(first) + + def test_interrupted_capture_can_retry(self): + previous = self.prepare() + self.write(JSON_HEADER, "new generation") + trap = self.root / "interruption" + trap.mkdir() + first, ready = trap / "first", trap / "ready" + # Pause the second index read, after the new files are staged and before + # publication. Terminate the whole fixture process group at that point. + shim = trap / "git" + shim.write_text("#!/bin/sh\nfor arg do\n if [ \"$arg\" = ls-files ]; then\n" + f" if [ -f {shlex.quote(str(first))} ]; then\n" + f" touch {shlex.quote(str(ready))}\n exec sleep 20\n fi\n" + f" touch {shlex.quote(str(first))}\n fi\ndone\n" + f"exec {shlex.quote(shutil.which('git'))} \"$@\"\n") + shim.chmod(0o755) + with subprocess.Popen([self.tool, "--source", self.source], start_new_session=True, + env=self.env | {"PATH": f"{trap}:{self.env['PATH']}"}) as proc: + try: + timeout = time.monotonic() + 5 + while not ready.exists() and proc.poll() is None and time.monotonic() < timeout: + time.sleep(0.005) + self.assertTrue(ready.exists()) + finally: + if proc.poll() is None: + os.killpg(proc.pid, signal.SIGKILL) + self.assertEqual(proc.wait(timeout=5), -signal.SIGKILL) + self.assertEqual(self.current.resolve(strict=True), previous) + self.assertTrue(self.check_generation(self.prepare())["dirty"]) + self.assertFalse(self.check_generation(previous)["dirty"]) + + def test_rejects_unowned_layout_or_damaged_generation(self): + previous = self.prepare() + # Simulate a damaged store in an isolated fixture. + previous.chmod(0o755) + (previous / "build.cpp").write_text("unexpected fixture entry") + previous.chmod(0o555) + self.assertIn("unexpected entries", self.failed_update(previous)) + sources = self.store / "sources" + moved = self.root / "moved-sources" + sources.rename(moved) + sources.symlink_to(moved, target_is_directory=True) + result = self.cli("--source", self.source) + self.assertNotEqual(result.returncode, 0) + self.assertIn("owned directory", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/native/StockDiagnostics.py b/tests/native/StockDiagnostics.py new file mode 100644 index 0000000..e07f098 --- /dev/null +++ b/tests/native/StockDiagnostics.py @@ -0,0 +1,238 @@ +"""Exercise stock GCC diagnostics over the installed server's normal LSP transport.""" +import argparse +import json +import os +from pathlib import Path +import queue +import subprocess +import tempfile +import threading +import time + + +class Editor: + def __init__(self, binary, profile, root, provider, versions=True): + self.errors = tempfile.TemporaryFile() + self.process = subprocess.Popen( + [binary, "--stdio", "--workspace-root", root, "--provider", provider, + "--gcc-profile", profile], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=self.errors, cwd=root, env={"LC_ALL": "C", "PATH": ""}) + self.messages = queue.Queue() + self.pending = [] + self.sequence = 0 + self.reader = threading.Thread(target=self.read, daemon=True) + self.reader.start() + try: + result = self.request("initialize", { + "capabilities": {"textDocument": {"publishDiagnostics": {"versionSupport": versions}}}, + "workspaceFolders": [{"uri": root.as_uri(), "name": root.name}]}) + assert result["capabilities"]["textDocumentSync"]["openClose"] + self.send("initialized", {}) + except BaseException: + self.dispose() + raise + + def read(self): + try: + stream = self.process.stdout + while line := stream.readline(8192): + assert line.startswith(b"Content-Length: ") and line.endswith(b"\r\n") + size = int(line[16:]) + assert 0 < size <= 16 * 1024 * 1024 and stream.readline(8192) == b"\r\n" + self.messages.put(json.loads(stream.read(size))) + except Exception as exc: + self.messages.put(exc) + finally: + self.messages.put(EOFError("server stdout closed")) + + def send(self, method, params, **fields): + body = json.dumps({"jsonrpc": "2.0", "method": method, "params": params, **fields}).encode() + self.process.stdin.write(f"Content-Length: {len(body)}\r\n\r\n".encode() + body) + self.process.stdin.flush() + + def wait(self, predicate, timeout=30): + end = time.monotonic() + timeout + while True: + for index, item in enumerate(self.pending): + if predicate(item): + return self.pending.pop(index) + try: + item = self.messages.get(timeout=max(0, end - time.monotonic())) + except queue.Empty: + raise AssertionError(f"timed out waiting for LSP output; pending={self.pending!r}") from None + if isinstance(item, Exception): + raise item + self.pending.append(item) + + def request(self, method, params): + self.sequence += 1 + self.send(method, params, id=self.sequence) + response = self.wait(lambda item: item.get("id") == self.sequence) + assert "error" not in response, response + return response["result"] + + def open(self, file, text, version=1): + self.send("textDocument/didOpen", {"textDocument": { + "uri": file.as_uri(), "languageId": "cpp", "version": version, "text": text}}) + + def change(self, file, version, text): + self.send("textDocument/didChange", {"textDocument": {"uri": file.as_uri(), "version": version}, + "contentChanges": [{"text": text}]}) + + def close(self, file): + self.send("textDocument/didClose", {"textDocument": {"uri": file.as_uri()}}) + + def status(self, file): + return self.request("voidLanguageServer/analysisStatus", {"textDocument": {"uri": file.as_uri()}}) + + def state(self, file, names, timeout=30): + end = time.monotonic() + timeout + while time.monotonic() < end: + status = self.status(file) + if status["state"] in names: + return status + time.sleep(.02) + raise AssertionError(f"missing analysis state {names}: {status}") + + def diagnostics(self, file, version, word=None, timeout=30): + def match(message): + if message.get("method") != "textDocument/publishDiagnostics": + return False + p = message["params"] + if p["uri"] != file.as_uri() or p.get("version") != version: + return False + return (not p["diagnostics"] if word is None else + any(word in d["message"] for d in p["diagnostics"])) + try: + return self.wait(match, timeout)["params"]["diagnostics"] + except AssertionError as err: + raise AssertionError(f"{err}; status={self.status(file)}") from err + + def finish(self): + assert self.request("shutdown", None) is None + self.send("exit", None) + self.process.stdin.close() + assert self.process.wait(timeout=10) == 0 + self.errors.seek(0) + assert self.errors.read() == b"" + + def __enter__(self): + return self + + def dispose(self): + if self.process.poll() is None: + self.process.kill() + self.process.wait() + if not self.process.stdin.closed: + self.process.stdin.close() + self.reader.join(timeout=5) + self.process.stdout.close() + self.errors.close() + + def __exit__(self, exc_type, *_): + try: + if exc_type is None: + self.finish() + finally: + self.dispose() + + +def simple(binary, profile, root): + driver = json.loads(profile.read_text())["driver"]["path"] + tu, header, optional = (root / s for s in ("main.cpp", "value.hpp", "optional.hpp")) + good = ('#include "value.hpp"\n#if __has_include("optional.hpp")\n' + 'int guard = optional_error;\n#endif\nint answer(){return value();}\n') + tu.write_text(good) + header.write_text('static_assert(!__builtin_strcmp(__TIMESTAMP__, "Sat Jan 1 00:00:00 2000"));\n' + 'inline int value(){return 7;}\n') + os.utime(header, (946684800, 946684800)) + (root / "compile_commands.json").write_text(json.dumps([{ + "directory": str(root), "file": str(tu), "arguments": [driver, "-std=c++26", "-c", str(tu)]}])) + with Editor(binary, profile, root, "compdb") as e: + e.open(tu, good) + e.diagnostics(tu, 1) + bad = good.replace("return value()", "return wrong()") + e.change(tu, 2, bad) + diag = e.diagnostics(tu, 2, "wrong")[0] + assert diag["range"] == {"start": {"line": 4, "character": 20}, + "end": {"line": 4, "character": 25}}, diag + assert diag["severity"] == 1 and diag["source"] == "gcc" + e.change(tu, 3, good) + e.diagnostics(tu, 3) + e.open(header, "inline int renamed(){return 7;}\n") + e.diagnostics(tu, 3, "value") + e.close(header) + e.diagnostics(tu, 3) + # No incoming protocol message triggers either of the next two disk changes. + optional.write_text("// appeared after the last successful analysis\n") + e.diagnostics(tu, 3, "optional_error") + optional.unlink() + e.diagnostics(tu, 3) + e.state(tu, {"ready"}) + e.change(tu, 4, bad) + e.change(tu, 5, good) + e.diagnostics(tu, 5) + assert all(m.get("params", {}).get("version") != 4 for m in e.pending) + # A same-spelling #line origin in a header cannot point at inactive code in main. + (root / "line.hpp").write_text(f'#line 2 "{tu}"\nint x = impostor;\n') + e.change(tu, 6, '#if 0\nint x = impostor;\n#endif\n#include "line.hpp"\n') + report = e.state(tu, {"partial"}) + assert report["unlocatedCount"] and any("impostor" in m for m in report["messages"]), report + e.close(tu) + e.open(tu, good) + e.diagnostics(tu, 1) + e.close(tu) + e.diagnostics(tu, 1) + with Editor(binary, profile, root, "compdb", versions=False) as e: + e.open(tu, bad) + e.diagnostics(tu, None, "wrong") + db = root / "compile_commands.json" + saved_db = db.read_bytes() + db.unlink() + with Editor(binary, profile, root, "compdb") as e: + e.open(tu, bad) + e.state(tu, {"unavailable"}) + db.write_bytes(saved_db) + e.diagnostics(tu, 1, "wrong") + db.unlink() + e.diagnostics(tu, 1) + assert e.state(tu, {"unavailable"})["compilerRuns"] == 0 + print("compdb: exact range, unsaved header, disk timestamp, idle header and database changes, supersession, remap, reopen and version negotiation passed", flush=True) + + +def actual(binary, profile, root): + tu = root / "src/Documents/DocumentSnapshot.cpp" + saved = tu.read_text() + assert saved.count("Void::Hash::fnv1a64(text)") == 1 + edited = saved.replace("Void::Hash::fnv1a64(text)", "Void::Hash::missing(text)") + with Editor(binary, profile, root, "vbs") as e: + e.open(tu, edited) + diag = e.diagnostics(tu, 1, "missing", 90)[0] + assert diag["range"] == {"start": {"line": 18, "character": 33}, + "end": {"line": 18, "character": 40}}, diag + status = e.status(tu) + assert status["state"] == "ready" and status["provider"] == "vbs", status + cold = status["compilerRuns"] + e.change(tu, 2, saved) + e.diagnostics(tu, 2, timeout=90) + warm = e.status(tu)["compilerRuns"] + # Cancel a running compiler job, then observe only the newer editor version. + e.change(tu, 3, edited) + e.state(tu, {"running"}) + e.change(tu, 4, saved) + e.diagnostics(tu, 4, timeout=90) + assert all(m.get("params", {}).get("version") != 3 for m in e.pending) + print(f"native VBS: edited DocumentSnapshot.cpp line 19, recovery and in-flight cancellation passed; GCC runs cold={cold} warm={warm}", flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--server", required=True, type=Path) + parser.add_argument("--gcc-profile", required=True, type=Path) + parser.add_argument("--vbs-workspace", type=Path) + args = parser.parse_args() + binary, profile = args.server.resolve(), args.gcc_profile.resolve() + with tempfile.TemporaryDirectory(prefix="vls-stock-editor-") as tmp: + simple(binary, profile, Path(tmp).resolve()) + if args.vbs_workspace: + actual(binary, profile, args.vbs_workspace.resolve()) diff --git a/tests/native/StockOccurrences.py b/tests/native/StockOccurrences.py new file mode 100644 index 0000000..53b27e0 --- /dev/null +++ b/tests/native/StockOccurrences.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 +"""Exercise stock-observer hover and definition through a real stdio LSP session.""" + +import argparse +import json +import os +from pathlib import Path +import select +import subprocess +import tempfile +import time + + +TU = Path("src/Documents/DocumentSnapshot.cpp") + + +def check(condition, detail): + if not condition: + raise ValueError(detail) + + +def utf16_position(text, offset): + line = text.count("\n", 0, offset) + start = text.rfind("\n", 0, offset) + 1 + return line, len(text[start:offset].encode("utf-16-le")) // 2 + + +def frame(message): + payload = json.dumps({"jsonrpc": "2.0", **message}, ensure_ascii=False).encode() + return f"Content-Length: {len(payload)}\r\n\r\n".encode() + payload + + +class Session: + def __init__(self, argv, cwd, stderr): + self.process = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=stderr, + env={**os.environ, "LC_ALL": "C"}) + self.sequence = 0 + self.buffer = b"" + + def send(self, message): + self.process.stdin.write(frame(message)) + self.process.stdin.flush() + + def notify(self, method, params): + self.send({"method": method, "params": params}) + + def request(self, method, params, timeout=90): + self.sequence += 1 + self.send({"id": self.sequence, "method": method, "params": params}) + deadline = time.monotonic() + timeout + while True: + message = self.read(deadline - time.monotonic()) + if message.get("id") == self.sequence: + return message + + def read(self, timeout): + if timeout <= 0: + raise TimeoutError("LSP response deadline expired") + while b"\r\n\r\n" not in self.buffer: + ready, _, _ = select.select([self.process.stdout], [], [], timeout) + if not ready: + raise TimeoutError("LSP response deadline expired") + chunk = os.read(self.process.stdout.fileno(), 65536) + check(chunk, "the server closed stdout") + self.buffer += chunk + header, rest = self.buffer.split(b"\r\n\r\n", 1) + length = int(header.removeprefix(b"Content-Length: ")) + while len(rest) < length: + chunk = os.read(self.process.stdout.fileno(), 65536) + check(chunk, "truncated LSP response") + rest += chunk + body, self.buffer = rest[:length], rest[length:] + return json.loads(body) + + def close(self): + try: + self.request("shutdown", None) + self.notify("exit", None) + except (OSError, TimeoutError, ValueError): + pass + try: + self.process.stdin.close() + except OSError: + pass + try: + self.process.wait(timeout=10) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + + +def await_analysis(session, uri, expected_version=None, timeout=120): + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + reply = session.request("voidLanguageServer/analysisStatus", + {"textDocument": {"uri": uri}}, timeout=30) + result = reply.get("result") or {} + last = result + state = result.get("state") + version = result.get("version") + if state == "unavailable": + raise ValueError(f"analysis unavailable: {result.get('detail')}") + if state in ("ready", "partial") and ( + expected_version is None or version == expected_version): + return result + time.sleep(0.2) + raise ValueError(f"analysis did not finish: {last}") + + +def await_module_scan(session, uri, timeout=180): + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + reply = session.request("voidLanguageServer/analysisStatus", + {"textDocument": {"uri": uri}}, timeout=30) + result = reply.get("result") or {} + last = result.get("moduleScan") + if last and last.get("state") in ("ready", "partial"): + return last + if last and last.get("state") in ("failed", "unavailable", "cancelled"): + raise ValueError(f"module scan did not complete: {last} status={result}") + time.sleep(0.2) + raise ValueError(f"module scan did not finish: {last}") + + +def overload_lines(header): + lines = header.read_text(encoding="utf-8").splitlines() + found = {} + for number, line in enumerate(lines, 1): + if "fnv1a64(std::string_view s)" in line: + found["string_view"] = number + if "fnv1a64(std::span data)" in line: + found["byte_span"] = number + check(set(found) == {"string_view", "byte_span"}, f"missing overloads in {header}") + return found + + +def run(server, profile, workspace, header): + text = (workspace / TU).read_text(encoding="utf-8") + call = "Void::Hash::fnv1a64(text)" + check(text.count(call) == 1, "the real Void overload witness changed") + start = text.index(call) + name_start = start + len("Void::Hash::") + line, character = utf16_position(text, name_start) + argument = start + len("Void::Hash::fnv1a64(") + argument_line, argument_character = utf16_position(text, argument) + uri = (workspace / TU).as_uri() + lines = overload_lines(header) + with tempfile.TemporaryFile() as errors: + session = Session([str(server), "--stdio", "--workspace-root", str(workspace), + "--gcc-profile", str(profile)], workspace, errors) + try: + initialized = session.request("initialize", { + "processId": None, "capabilities": {}, + "workspaceFolders": [{"uri": workspace.as_uri(), "name": workspace.name}]}) + capabilities = initialized["result"]["capabilities"] + check(capabilities.get("hoverProvider") and capabilities.get("definitionProvider"), + f"observer capabilities are not advertised: {capabilities}") + session.notify("initialized", {}) + session.notify("textDocument/didOpen", {"textDocument": { + "uri": uri, "languageId": "cpp", "version": 1, "text": text}}) + status = await_analysis(session, uri, expected_version=1) + + position = {"line": line, "character": character} + hover = session.request("textDocument/hover", + {"textDocument": {"uri": uri}, "position": position}) + check(hover.get("result"), f"no hover fact: {hover} status={status}") + contents = hover["result"]["contents"]["value"] + check("fnv1a64" in contents and "string_view" in contents, + f"unexpected hover contents: {contents}") + + definition = session.request("textDocument/definition", + {"textDocument": {"uri": uri}, "position": position}) + location = definition.get("result") + check(location and location["uri"].endswith("Void/Core/Hash.hpp"), + f"wrong definition: {definition}") + check(location["range"]["start"]["line"] + 1 == lines["string_view"], + f"string_view overload not selected: {location} vs {lines}") + + session.notify("textDocument/didChange", { + "textDocument": {"uri": uri, "version": 2}, + "contentChanges": [{ + "range": {"start": {"line": argument_line, "character": argument_character}, + "end": {"line": argument_line, + "character": argument_character + len("text")}}, + "text": "std::as_bytes(std::span{text})"}]}) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + running = session.request("voidLanguageServer/analysisStatus", + {"textDocument": {"uri": uri}}, timeout=30) + if (running.get("result") or {}).get("state") == "running": + break + time.sleep(0.02) + else: + raise ValueError("the second revision never started running") + edited = (text[:argument] + "std::as_bytes(std::span{text})" + + text[argument + len("text"):]) + session.notify("textDocument/didChange", { + "textDocument": {"uri": uri, "version": 3}, + "contentChanges": [{ + "range": {"start": {"line": edited.count("\n"), "character": 0}, + "end": {"line": edited.count("\n"), "character": 0}}, + "text": "// scheduler coalescing\n"}]}) + status = await_analysis(session, uri, expected_version=3) + check(status.get("scheduler", {}).get("cancelled", 0) >= 1, + f"the superseded revision was not cancelled: {status.get('scheduler')}") + definition = session.request("textDocument/definition", + {"textDocument": {"uri": uri}, "position": position}) + location = definition.get("result") + check(location and location["range"]["start"]["line"] + 1 == lines["byte_span"], + f"byte_span overload not selected after the edit: {definition} vs {lines}") + + scan = await_module_scan(session, uri) + check(isinstance(scan.get("provides"), list) and + isinstance(scan.get("imports"), list), + f"module scan has no verified rule: {scan}") + + symbols = session.request("workspace/symbol", {"query": "fnv1a64"}) + found = [symbol for symbol in (symbols.get("result") or []) + if symbol["location"]["uri"].endswith("Void/Core/Hash.hpp")] + check(found and any(symbol["name"] == "fnv1a64" for symbol in found), + f"workspace symbol did not reach the Hash.hpp definition: {symbols} status={status}") + empty = session.request("workspace/symbol", {"query": "no-such-symbol"}) + check(empty.get("result") == [], f"unexpected workspace symbol result: {empty}") + + references = session.request("textDocument/references", + {"textDocument": {"uri": uri}, "position": position}) + check(references.get("error") and references["error"]["code"] == -32803 and + "incomplete" in references["error"]["message"], + f"references were presented as complete: {references}") + prepare = session.request("textDocument/prepareRename", + {"textDocument": {"uri": uri}, "position": position}) + check(prepare.get("error") and prepare["error"]["code"] == -32803, + f"prepareRename did not refuse incomplete coverage: {prepare}") + rename = session.request("textDocument/rename", + {"textDocument": {"uri": uri}, "position": position, + "newName": "renamed_fnv"}) + check(rename.get("error") and rename["error"]["code"] == -32803 and + "incomplete" in rename["error"]["message"], + f"rename was not guarded: {rename}") + + missing = session.request("textDocument/definition", { + "textDocument": {"uri": uri}, + "position": {"line": 0, "character": 0}}) + check(missing.get("result") is None, f"definition for an unrelated position: {missing}") + finally: + session.close() + errors.seek(0) + diagnostics = errors.read() + check(b"fatal" not in diagnostics.lower(), f"server stderr: {diagnostics[-800:]!r}") + print(f"stock occurrences: hover and definition selected string_view at " + f"Hash.hpp:{lines['string_view']} then byte_span at {lines['byte_span']}; " + f"module scan {scan['state']}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--server", required=True, type=Path) + parser.add_argument("--gcc-profile", required=True, type=Path) + parser.add_argument("--workspace", type=Path, default=Path.cwd()) + parser.add_argument("--header", type=Path, + default=Path("build/voidlibrary/current/include/Void/Core/Hash.hpp")) + options = parser.parse_args() + run(options.server.resolve(strict=True), options.gcc_profile.resolve(strict=True), + options.workspace.resolve(strict=True), options.header.resolve(strict=True)) + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, subprocess.SubprocessError) as exc: + raise SystemExit(f"verify-stock-occurrences: {exc}") diff --git a/tests/native/VscodeClient.py b/tests/native/VscodeClient.py new file mode 100644 index 0000000..979b3f8 --- /dev/null +++ b/tests/native/VscodeClient.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Run the VS Code client acceptance in a disposable extension host.""" + +import argparse +import os +from pathlib import Path +import shutil +import subprocess +import tempfile + + +ROOT = Path(__file__).resolve().parents[2] +CLIENT = ROOT / "clients/vscode" + + +def check(condition, detail): + if not condition: + raise ValueError(detail) + + +def application(code): + """The Nix `code` wrapper starts a detached CLI; the app binary runs tests in-process.""" + resolved = code.resolve(strict=True) + candidate = resolved.parent.parent / "lib/vscode/code" + return candidate if candidate.is_file() else resolved + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--code", default=shutil.which("code"), + help="VS Code launcher (default: code on PATH)") + parser.add_argument("--server", required=True, type=Path) + parser.add_argument("--adapter", required=True, type=Path) + parser.add_argument("--trace", required=True, type=Path) + parser.add_argument("--timeout", type=float, default=240) + options = parser.parse_args() + check(options.code, "code is not on PATH") + check((CLIENT / "node_modules").is_dir(), + "run `npm install` in clients/vscode once as a development step") + subprocess.run(["npm", "run", "compile"], cwd=CLIENT, check=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + tests = CLIENT / "out/test/run.js" + check(tests.is_file(), "the extension test entry was not compiled") + executable = application(Path(options.code)) + server = options.server.resolve(strict=True) + adapter = options.adapter.resolve(strict=True) + trace = options.trace.resolve(strict=True) + with tempfile.TemporaryDirectory(prefix="vls-vscode-client-") as temp: + work = Path(temp) + workspace = work / "workspace" + workspace.mkdir() + (workspace / "unit.cpp").write_text("int value = 17;\nint read() { return value; }\n", + encoding="utf-8") + command = [ + str(executable), + f"--extensionDevelopmentPath={CLIENT}", + f"--extensionTestsPath={tests}", + f"--user-data-dir={work / 'user'}", + f"--extensions-dir={work / 'extensions'}", + "--no-sandbox", "--disable-gpu", "--disable-workspace-trust", + "--skip-welcome", "--skip-release-notes", + str(workspace), + ] + environment = {**os.environ, "VLS_SERVER": str(server), "VLS_DAP": str(adapter), + "VLS_TRACE": str(trace)} + result = subprocess.run(command, env=environment, capture_output=True, text=True, + timeout=options.timeout) + output = result.stdout + result.stderr + if result.returncode != 0 or "VSCODE_CLIENT_PASS" not in output: + print(output[-5000:]) + raise SystemExit(f"VS Code client acceptance failed (exit {result.returncode})") + print("VS Code client passed: LSP status, replay session, timeline, source, stale " + "rejection and transactional rename") + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, subprocess.SubprocessError) as exc: + raise SystemExit(f"verify-vscode-client: {exc}") diff --git a/tests/navigation/NavigationTests.cpp b/tests/navigation/NavigationTests.cpp new file mode 100644 index 0000000..ae73458 --- /dev/null +++ b/tests/navigation/NavigationTests.cpp @@ -0,0 +1,183 @@ +#include + +#include +#include + +#include +#include +#include + +namespace { +using namespace vls::navigation; +using Void::Testing::expect; +using Void::Testing::require; + +Location location(std::string path, std::uint32_t line) { + return {std::move(path), Range{{line, 0}, {line, 4}}}; +} + +Fact fact(std::string name, std::optional definition, std::string context, + std::string source, std::uint32_t line, bool editable = true) { + return {Binding{std::move(name), std::move(definition)}, + std::move(context), + std::move(source), + "content-1", + Range{{line, 0}, {line, 4}}, + editable, + "gcc"}; +} + +FactSet set(std::vector facts, bool complete = true) { + FactSet result; + result.facts = std::move(facts); + result.contexts = {{"debug:unit", complete, complete ? "" : "system headers"}}; + for (const auto &item : result.facts) + result.current_sources[item.source] = item.content; + return result; +} +} // namespace + +VOID_TEST(Navigation, resolves_unique_binding) { + const auto facts = set({fact("f", std::nullopt, "debug:unit", "/project/unit.cpp", 3)}); + const auto binding = binding_at(facts, "/project/unit.cpp", {3, 1}); + require(binding.has_value()); + expect(binding->name == "f"); + expect(!binding_at(facts, "/project/unit.cpp", {9, 0}).has_value()); +} + +VOID_TEST(Navigation, distinguishes_same_spelling_by_definition) { + const auto first = location("/project/a.hpp", 1), second = location("/project/b.hpp", 2); + const auto facts = set({fact("f", first, "debug:a", "/project/a.cpp", 3), + fact("f", second, "debug:b", "/project/b.cpp", 3)}); + const auto a = binding_at(facts, "/project/a.cpp", {3, 0}); + const auto b = binding_at(facts, "/project/b.cpp", {3, 0}); + require(a.has_value() && b.has_value()); + expect(a->definition == first && b->definition == second && !(a == b)); +} + +VOID_TEST(Navigation, ambiguous_overlapping_bindings_are_not_resolved_by_order) { + const auto facts = + set({fact("f", location("/project/a.hpp", 1), "debug:a", "/project/u.cpp", 3), + fact("f", location("/project/b.hpp", 1), "debug:b", "/project/u.cpp", 3)}); + const auto binding = binding_at(facts, "/project/u.cpp", {3, 0}); + require(!binding.has_value()); + expect(binding.error() == Refusal::ambiguous_binding); +} + +VOID_TEST(Navigation, references_are_deduplicated_and_sorted) { + const auto definition = location("/project/a.hpp", 1); + const auto facts = set({fact("f", definition, "debug:a", "/project/a.cpp", 5), + fact("f", definition, "debug:a", "/project/a.cpp", 5), + fact("f", definition, "debug:b", "/project/b.cpp", 2)}); + const auto binding = Binding{"f", definition}; + const auto result = references(facts, binding); + require(result.coverage_complete && !result.truncated); + require(result.locations.size() == 2); + expect(result.locations[0] == (Location{"/project/a.cpp", {{5, 0}, {5, 4}}})); + expect(result.locations[1].path == "/project/b.cpp"); +} + +VOID_TEST(Navigation, references_report_incomplete_coverage) { + const auto facts = set({fact("f", std::nullopt, "debug:unit", "/project/unit.cpp", 3)}, false); + const auto result = references(facts, Binding{"f", std::nullopt}); + expect(!result.coverage_complete); + expect(result.incomplete_contexts == std::vector{"debug:unit"}); + expect(result.locations.size() == 1); +} + +VOID_TEST(Navigation, references_truncate) { + std::vector facts; + for (std::uint32_t line = 0; line != 5; ++line) + facts.push_back(fact("f", std::nullopt, "debug:unit", "/project/unit.cpp", line)); + const auto result = references(set(std::move(facts)), Binding{"f", std::nullopt}, 2); + expect(result.locations.size() == 2 && result.truncated); +} + +VOID_TEST(Navigation, rename_is_ready_for_one_transactional_file) { + const auto definition = location("/project/a.hpp", 1); + const auto facts = set({fact("f", definition, "debug:a", "/project/a.cpp", 5), + fact("f", definition, "debug:b", "/project/b.cpp", 2)}); + const auto plan = prepare_rename(facts, "/project/a.cpp", {5, 0}, "renamed", true); + require(plan.ready()); + require(plan.edits.size() == 2); + expect(plan.edits[0].path == "/project/a.cpp" && plan.edits[0].replacement == "renamed"); + expect(plan.edits[1].path == "/project/b.cpp"); +} + +VOID_TEST(Navigation, rename_refuses_incomplete_coverage) { + const auto facts = set({fact("f", std::nullopt, "debug:unit", "/project/unit.cpp", 3)}, false); + const auto plan = prepare_rename(facts, "/project/unit.cpp", {3, 0}, "renamed", true); + expect(plan.refusal == Refusal::incomplete_coverage && !plan.ready()); + expect(plan.detail.contains("system headers")); +} + +VOID_TEST(Navigation, rename_refuses_a_stale_source) { + auto facts = set({fact("f", std::nullopt, "debug:unit", "/project/unit.cpp", 3)}); + facts.current_sources["/project/unit.cpp"] = "content-2"; + const auto plan = prepare_rename(facts, "/project/unit.cpp", {3, 0}, "renamed", true); + expect(plan.refusal == Refusal::stale_source); +} + +VOID_TEST(Navigation, rename_refuses_a_non_editable_origin) { + const auto facts = + set({fact("f", std::nullopt, "debug:unit", "/toolchain/header.hpp", 3, false)}); + const auto plan = prepare_rename(facts, "/toolchain/header.hpp", {3, 0}, "renamed", true); + expect(plan.refusal == Refusal::non_editable_origin); +} + +VOID_TEST(Navigation, rename_refuses_multi_file_without_a_transaction) { + const auto definition = location("/project/a.hpp", 1); + const auto facts = set({fact("f", definition, "debug:a", "/project/a.cpp", 5), + fact("f", definition, "debug:b", "/project/b.cpp", 2)}); + expect(prepare_rename(facts, "/project/a.cpp", {5, 0}, "renamed", false).refusal == + Refusal::multi_file_without_transaction); +} + +VOID_TEST(Navigation, rename_refuses_invalid_generated_and_unchanged_names) { + const auto facts = set({fact("f", std::nullopt, "debug:unit", "/project/unit.cpp", 3)}); + expect(prepare_rename(facts, "/project/unit.cpp", {3, 0}, "1bad", true).refusal == + Refusal::invalid_name); + expect(prepare_rename(facts, "/project/unit.cpp", {3, 0}, "f$generated", true).refusal == + Refusal::invalid_name); + expect(prepare_rename(facts, "/project/unit.cpp", {3, 0}, "f", true).refusal == + Refusal::unchanged_name); +} + +VOID_TEST(Navigation, rename_refuses_an_unknown_binding) { + const auto facts = set({fact("f", std::nullopt, "debug:unit", "/project/unit.cpp", 3)}); + expect(prepare_rename(facts, "/project/unit.cpp", {9, 0}, "renamed", true).refusal == + Refusal::unknown_binding); +} + +VOID_TEST(Navigation, references_and_rename_cover_other_contexts) { + const auto definition = location("/project/shared.hpp", 1); + auto facts = set({fact("f", definition, "debug:a", "/project/a.cpp", 5), + fact("f", definition, "debug:b", "/project/b.cpp", 2)}); + facts.contexts.push_back({"debug:b", true, ""}); + const auto binding = Binding{"f", definition}; + const auto result = references(facts, binding); + expect(result.coverage_complete && result.locations.size() == 2); + const auto plan = prepare_rename(facts, "/project/a.cpp", {5, 0}, "renamed", true); + require(plan.ready()); + expect(plan.edits.size() == 2); +} + +VOID_TEST(Navigation, rename_refuses_when_another_context_is_incomplete) { + const auto definition = location("/project/shared.hpp", 1); + auto facts = set({fact("f", definition, "debug:a", "/project/a.cpp", 5), + fact("f", definition, "debug:b", "/project/b.cpp", 2)}); + facts.contexts.push_back({"debug:b", false, "system headers"}); + const auto plan = prepare_rename(facts, "/project/a.cpp", {5, 0}, "renamed", true); + expect(plan.refusal == Refusal::incomplete_coverage); + expect(plan.detail.contains("debug:b")); +} + +VOID_TEST(Navigation, other_context_same_spelling_binding_is_not_renamed) { + const auto first = location("/project/a.hpp", 1), second = location("/project/b.hpp", 2); + auto facts = set({fact("f", first, "debug:a", "/project/a.cpp", 5), + fact("f", second, "debug:b", "/project/b.cpp", 2)}); + facts.contexts.push_back({"debug:b", true, ""}); + const auto plan = prepare_rename(facts, "/project/a.cpp", {5, 0}, "renamed", true); + require(plan.ready()); + expect(plan.edits.size() == 1 && plan.edits[0].path == "/project/a.cpp"); +} diff --git a/tests/performance/document_sync.py b/tests/performance/document_sync.py new file mode 100644 index 0000000..de78029 --- /dev/null +++ b/tests/performance/document_sync.py @@ -0,0 +1,117 @@ +"""Measure an incremental edit and the following JSON-RPC round trip on Linux.""" + +import argparse +import json +import math +from pathlib import Path +import resource +import signal +import statistics +import subprocess +import tempfile +import time + + +def send(server, message): + body = json.dumps({"jsonrpc": "2.0", **message}, separators=(",", ":")).encode() + server.stdin.write(f"Content-Length: {len(body)}\r\n\r\n".encode() + body) + server.stdin.flush() + + +def request(server, ident, method, params=None): + message = {"id": ident, "method": method} + if params is not None: + message["params"] = params + send(server, message) + header = server.stdout.readline(100) + if not header.startswith(b"Content-Length: ") or server.stdout.readline(3) != b"\r\n": + raise ValueError(f"unexpected response frame {header!r}") + length = int(header.split(b":", 1)[1]) + if not 0 < length < 8192: + raise ValueError("unexpected response size") + response = json.loads(server.stdout.read(length)) + if response.get("id") != ident: + raise ValueError("response ID mismatch") + return response + + +def measure(executable, size, samples, long_line=None): + with tempfile.TemporaryDirectory() as work, subprocess.Popen( + [str(executable), "--stdio"], cwd=work, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + ) as server: + try: + result = request(server, 1, "initialize", {}) + if result["result"]["capabilities"]["textDocumentSync"]["change"] != 2: + raise ValueError("server does not support incremental synchronization") + send(server, {"method": "initialized", "params": {}}) + uri = "untitled:document-edit-benchmark" + column = 2 + if long_line: + text = "a" * size + line_count = 1 + if long_line == "end": + column = size - 3 + else: + line = "a" * 63 + "\n" + line_count = size // len(line) + text = line * line_count + document = {"uri": uri, "languageId": "cpp", "version": 1, "text": text} + send(server, {"method": "textDocument/didOpen", "params": {"textDocument": document}}) + # An unknown request is a synchronously observable barrier in this session. + def barrier(ident): + if request(server, ident, "void-benchmark/barrier")["error"]["code"] != -32601: + raise ValueError("unexpected barrier result") + + barrier(2) + timings = [] + for sample in range(samples): + index = (sample * 7919) % line_count + selection = {"start": {"line": index, "character": column}, + "end": {"line": index, "character": column + 1}} + change = {"range": selection, "text": chr(65 + sample % 26)} + start = time.perf_counter_ns() + send(server, {"method": "textDocument/didChange", "params": { + "textDocument": {"uri": uri, "version": sample + 2}, "contentChanges": [change], + }}) + barrier(sample + 3) + timings.append((time.perf_counter_ns() - start) / 1e6) + send(server, {"method": "textDocument/didClose", "params": {"textDocument": {"uri": uri}}}) + if request(server, samples + 3, "shutdown")["result"] is not None: + raise ValueError("unexpected shutdown result") + send(server, {"method": "exit"}) + server.stdin.close() + if server.wait(timeout=5) != 0 or server.stderr.read(4096) or server.stdout.read(1): + raise RuntimeError("server emitted diagnostics, extra output, or a nonzero exit") + finally: + if server.poll() is None: + server.kill() + server.wait() + result = { + "document_bytes": size, "samples": samples, + "median_ms": round(statistics.median(timings), 2), + "p95_ms": round(sorted(timings)[math.ceil(samples * .95) - 1], 2), + "peak_rss_kib": resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss, + } + if long_line: + result.update(long_line=long_line, total_ms=round(sum(timings), 2)) + return result + + +def timed_out(signum, frame): + raise TimeoutError("document benchmark exceeded its 120 second deadline") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("server", type=Path) + workload = parser.add_mutually_exclusive_group() + workload.add_argument("--mib", type=int, choices=(1, 4, 8), default=1) + workload.add_argument("--long-line", choices=("start", "end"), + help="edit near the start or end of one 64 KiB ASCII line") + parser.add_argument("--samples", type=int, choices=range(1, 101), metavar="1..100", default=20) + args = parser.parse_args() + signal.signal(signal.SIGALRM, timed_out) + signal.alarm(120) + size = 64 << 10 if args.long_line else args.mib << 20 + print(json.dumps(measure(args.server.resolve(strict=True), size, args.samples, args.long_line))) diff --git a/tests/providers/CommandImportTests.cpp b/tests/providers/CommandImportTests.cpp new file mode 100644 index 0000000..c7abc2e --- /dev/null +++ b/tests/providers/CommandImportTests.cpp @@ -0,0 +1,605 @@ +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { +using namespace Void::LanguageServer::Build; +using namespace std::string_view_literals; +namespace Workspace = Void::LanguageServer::Workspace; +namespace Protocol = Void::LanguageServer::Protocol; +namespace fs = std::filesystem; +using Protocol::Json; +using Strings = std::vector; +using Void::Testing::expect; +using Void::Testing::require; + +void write_file(const fs::path &path, std::string_view bytes) { + std::ofstream output(path, std::ios::binary); + output.write(bytes.data(), static_cast(bytes.size())); + output.close(); + require(output.good()); +} + +std::string encode(const Json &value) { + auto encoded = Protocol::serialize_json(value); + require(encoded.has_value()); + return *encoded; +} + +std::string command_row(std::string command, std::string file = "unit.cpp") { + return encode(Json{Json::Object{{"directory", Json{std::string{"."}}}, + {"file", Json{std::move(file)}}, + {"command", Json{std::move(command)}}}}); +} + +std::string argv_row(const Strings &argv, std::string file = "unit.cpp", std::string cwd = ".", + std::optional output = {}, std::optional command = {}) { + Json::Array array; + for (const auto &arg : argv) + array.push_back(Json{arg}); + Json::Object row{{"directory", Json{std::move(cwd)}}, {"file", Json{std::move(file)}}, + {"arguments", Json{std::move(array)}}}; + if (output) + row["output"] = Json{*output}; + if (command) + row["command"] = Json{*command}; + return encode(Json{std::move(row)}); +} + +ProviderScope bind(const fs::path &root) { + auto scope = bind_provider_scope({.workspace = {root, "rows-test"}}); + require(scope.has_value()); + return *scope; +} + +struct Fixture { + Void::FileSystem::TempDir temp{"vls_rows_"}; + fs::path root = temp.path() / "work"; + fs::path base = root / "metadata", database = base / "compile_commands.json"; + fs::path gcc = temp.path() / "g++", clang = temp.path() / "clang++"; + ProviderScope scope; + + Fixture() { + fs::create_directories(base); + scope = bind(root); + for (const auto &tool : {gcc, clang}) { + write_file(tool, "compiler identity fixture"); + fs::permissions(tool, fs::perms::owner_read | fs::perms::owner_exec); + } + } + + // Acquire real filesystem identities through the launcher's settings and pinning API. + DriverInput pin(Workspace::CompilerDriver dialect = Workspace::CompilerDriver::gcc, + Workspace::AuthorityLevel purpose = Workspace::AuthorityLevel::compiler_use, + const fs::path &workspace = {}) const { + const auto &owner = workspace.empty() ? root : workspace; + const auto &tool = dialect == Workspace::CompilerDriver::clang ? clang : gcc; + Workspace::SettingsOverrides overrides; + overrides.tool_approvals = std::vector{{owner, purpose, tool}}; + auto flags = Workspace::settings_from_cli(std::move(overrides), owner); + auto local = Workspace::parse_workspace_settings(Json{Json::Object{}}, owner); + Workspace::TrustPolicy policy; + auto generation = policy.replace_configuration(Workspace::merge_configuration(local, nullptr, &flags)); + require(generation.has_value()); + require(policy.pin_approved_tool(owner, purpose, tool).has_value()); + auto checked = policy.check_tool(owner, purpose, tool, *generation); + require(checked.has_value()); + return {std::move(*checked), dialect, {"ccache"}}; + } + + std::expected + import(std::string_view bytes, const std::optional &driver = {}, + const std::optional &profile = {}) const { + write_file(database, bytes); + auto acquired = read_provider_file(scope, database, FilePurpose::database, scope.limits.max_compdb_bytes); + if (!acquired) + return std::unexpected(acquired.error()); + return import_commands({scope, *acquired, profile, driver}); + } + ImportedCommands rows(std::initializer_list records, + const std::optional &driver = {}, + const std::optional &profile = {}) const { + std::string bytes = "[\n"; + for (const auto &record : records) { + if (bytes.size() > 2) + bytes += ",\n"; + bytes += record; + } + auto imported = import(bytes + "\n]", driver, profile); + require(imported.has_value()); + require(imported->contexts.size() == records.size()); + return std::move(*imported); + } +}; + +bool limited(const BuildContext &context, std::string_view fragment = {}) { + return !context.semantic_arguments && std::ranges::any_of(context.limitations, [&](const auto &reason) { + return reason.contains(fragment); + }); +} + +const Strings &semantic(const BuildContext &context) { + require(context.semantic_arguments.has_value()); + expect(context.limitations.empty()); + return *context.semantic_arguments; +} +} // namespace + +VOID_TEST(CommandImport, passive_rows_retain_exact_json_and_unknown_provenance) { + Fixture f; + const std::string raw = R"json({ "directory":"dir été", "file":"u\"{x}.cpp", + "arguments":["g++","-c","u\"{x}.cpp"], "vendor":{"nested":[true,{"x":"\\\"}]"}],"n":2.5} })json"; + const auto result = f.rows({raw}, {}, "debug"); + const auto &row = result.contexts.front(); + require(row.original && row.original->arguments); + expect(row.original->original_record == raw && row.original->metadata_file == f.database); + expect(!row.original->command && row.original->arguments->at(2) == "u\"{x}.cpp"); + expect(row.key.profile == "debug" && !row.key.target && row.key.role == ContextRole::unknown); + expect(row.key.owning_tu == f.base / "dir été" / "u\"{x}.cpp"); + expect(limited(row, "checked compiler") && !row.source_language); + require(row.sources.size() == 1); + expect(row.sources.front().source_path == row.key.owning_tu && !row.sources.front().compiler_path); + expect(row.sources.front().origin == SourceOrigin::unknown && + row.sources.front().editability == Editability::unknown); + expect(!row.toolchain && !row.standard_library && !row.environment && !row.prerequisites && !row.artifacts); + expect(result.dependencies.empty() && !result.revision.empty()); + expect(BuildGeneration::create({f.scope.workspace, "compdb", result.revision}, result.contexts).has_value()); +} + +VOID_TEST(CommandImport, malformed_structure_rejects_the_entire_database) { + Fixture f; + const auto good = argv_row({"c++", "-c", "a.cpp"}, "a.cpp"); + for (const auto &bad : {"null", "[]", "{}", R"({"directory":".","file":"b.cpp"})", + R"({"directory":2,"file":"b.cpp","arguments":[]})", + R"({"directory":".","file":"b.cpp","arguments":null,"command":"c++ -c b.cpp"})", + R"({"directory":".","file":"b.cpp","arguments":["c++",1],"command":"c++ -c b.cpp"})", + R"({"directory":".","file":"b.cpp","command":42,"arguments":["ok"]})", + R"({"directory":".","file":"b.cpp","arguments":[],"command":"c++ -c b.cpp"})", + R"({"directory":".","file":"b.cpp","output":false,"arguments":["cc"]})", + R"({"directory":".","file":"b.cpp","file":"c.cpp","command":""})", + R"({"directory":".","file":"b.cpp","arguments":["nul\u0000arg"]})", + R"({"directory":".","file":"\ud800","arguments":["cc"]})", R"({"x":[})"}) { + auto result = f.import("[" + good + "," + bad + "]"); + expect(!result.has_value()); + } + for (const auto &bad : {"", "{}", "[,]", "[{} ,]", "[]x", "[[]", "[\v]", "[\xff]"}) + expect(!f.import(bad)); + auto empty = f.import(" [ ]\t\n"); + require(empty.has_value()); + expect(empty->contexts.empty()); +} + +VOID_TEST(CommandImport, command_quoting_and_typed_arguments_precedence) { + Fixture f; + const auto checked = f.pin(); + const auto command = f.gcc.native() + + R"( -DNAME="has spaces and \"quotes\"" -I'include folder' -x c++ -c café\ source.cpp)"; + auto command_only = f.rows({command_row(command, "café source.cpp")}, checked); + const auto &c = command_only.contexts.front(); + expect(semantic(c) == Strings{f.gcc.native(), "-DNAME=has spaces and \"quotes\"", + "-I" + (f.base / "include folder").native(), "-x", "c++", "-c", (f.base / "café source.cpp").native()}); + expect(c.source_language == "c++" && c.original->command == command && !c.original->arguments); + const Strings typed{f.gcc.native(), "-DEXACT=$literal", "-c", "unit.cpp"}; + const auto secondary = "ignored && touch " + (f.temp.path() / "marker").native(); + auto both = f.rows({argv_row(typed, "unit.cpp", ".", {}, secondary)}, checked); + const auto &row = both.contexts.front(); + expect(semantic(row)[1] == typed[1] && row.original->arguments == typed && row.original->command == secondary); + expect(!fs::exists(f.temp.path() / "marker")); +} + +VOID_TEST(CommandImport, checked_driver_uses_the_language_of_the_actual_input_operand) { + Fixture f; + write_file(f.base / "generated.inc", "int value;\n"); + fs::create_symlink("generated.inc", f.base / "alias.cpp"); + for (const auto dialect : {Workspace::CompilerDriver::gcc, Workspace::CompilerDriver::clang}) { + const auto driver = f.pin(dialect); + const auto &tool = driver.tool.identity.selected_path.native(); + auto imported = f.rows({argv_row({tool, "-c", "alias.cpp"}, "generated.inc"), + argv_row({tool, "-xc", "-c", "unit.cpp"}), + argv_row({tool, "-c", "unit.cpp", "-x", "c"}), + argv_row({tool, "-c", "ordinary.h"}, "ordinary.h")}, driver); + const auto &rows = imported.contexts; + require(rows.size() == 4); + expect(rows[0].key.owning_tu == f.base / "generated.inc" && + rows[0].source_language == "c++"); + expect(rows[1].source_language == "c"); + expect(rows[2].source_language == "c++"); + expect(rows[3].semantic_arguments.has_value() && !rows[3].source_language); + } +} + +VOID_TEST(CommandImport, shell_constructs_and_incomplete_quoting_remain_passive) { + Fixture f; + const auto pin = f.pin(); + const auto marker = f.temp.path() / "marker"; + for (const std::string tail : {" && touch " + marker.native(), " -DA=$(touch " + marker.native() + ")", + std::string{" *.cpp"}, std::string{" > file"}, std::string{" -DNAME=\"$HOME\""}, + std::string{" -DNAME='broken"}, std::string{" \\"}}) { + const auto command = f.gcc.native() + " -c unit.cpp" + tail; + const auto result = f.rows({command_row(command)}, pin); + const auto &row = result.contexts.front(); + expect(limited(row) && row.original->command == command); + } + expect(!fs::exists(marker)); +} + +VOID_TEST(CommandImport, duplicate_and_conflicting_alternatives_survive_reordering) { + Fixture f; + const auto a = argv_row({"g++", "-c", "unit.cpp"}); + const auto b = argv_row({"g++", "-DOTHER", "-c", "unit.cpp"}); + const std::string extension = a.substr(0, a.size()-1) + ",\"mode\":\"vendor\"}"; + const auto ordered = f.rows({a, b, a, extension}); + const auto changed = f.rows({extension, a, a, b}); + auto alternatives = [](const auto &result) { + std::map values; + for (const auto &row : result.contexts) + expect(values.emplace(row.key.alternative, *row.original->original_record).second && + row.key.alternative == row.original->record_id); + return values; + }; + expect(alternatives(ordered) == alternatives(changed)); + const auto gen = BuildGeneration::create({f.scope.workspace, "compdb", ordered.revision}, ordered.contexts); + require(gen.has_value()); + expect((*gen)->candidates(f.base / "unit.cpp").size() == 4); +} + +VOID_TEST(CommandImport, relative_paths_use_logical_database_parent) { + Fixture f; + const auto actual = f.root / "actual"; + fs::create_directory(actual); + fs::create_symlink(actual / "commands.json", f.database); + const auto checked = f.pin(); + const auto row = argv_row({f.gcc.native(), "-c", "源.cpp", "-o", "obj/x.o"}, "源.cpp", "./build", + (f.base / "build/obj/x.o").native()); + const auto result = f.rows({row}, checked); + const auto &context = result.contexts.front(); + expect(context.working_directory == f.base / "build" && context.key.owning_tu == f.base / "build/源.cpp"); + expect(semantic(context) == Strings{f.gcc.native(), "-c", (f.base / "build/源.cpp").native()}); + expect(context.original->metadata_file == f.database); +} + +VOID_TEST(CommandImport, repeated_native_flags_and_cmake_output_are_preserved) { + Fixture f; + const auto pin = f.pin(); + const auto obj = (f.base / "obj/unit.cpp.o").native(); + const Strings native{f.gcc.native(), "-std=c++26", "-I", f.root.native(), "-I", f.root.native(), + "-O0", "-g", "-freflection", "-freflection", "-freflection", "-c", "unit.cpp", "-o", obj}; + const auto cmake = f.gcc.native() + " -I" + f.root.native() + + " -g -std=c++26 -Wall -Wextra -Wpedantic -freflection -o obj/unit.cpp.o -c unit.cpp"; + const auto named = argv_row(native, "unit.cpp", ".", obj); + auto cmake_row = command_row(cmake); + cmake_row.insert(cmake_row.size()-1, ",\"output\":" + encode(Json{obj})); + const auto result = f.rows({named, cmake_row}, pin); + expect(result.contexts[0].original->arguments == native && result.contexts[1].original->command == cmake); + expect(std::ranges::count(semantic(result.contexts[0]), "-freflection"sv) == 3); + for (const auto &row : result.contexts) { + expect(!std::ranges::contains(semantic(row), "-o"sv)); + expect(semantic(row).back() == (f.base / "unit.cpp").native()); + } + const auto passive = f.rows({named, cmake_row}); + expect(std::ranges::all_of(passive.contexts, [](const auto &row) { return limited(row); })); +} + +VOID_TEST(CommandImport, output_pair_requires_the_correct_option_boundary) { + Fixture f; + const auto pin = f.pin(); + const auto include = f.rows({argv_row({f.gcc.native(), "-I", "-o", "-c", "unit.cpp"})}, pin); + expect(semantic(include.contexts.front()) == + Strings{f.gcc.native(), "-I", (f.base / "-o").native(), "-c", (f.base / "unit.cpp").native()}); + const auto rejected = f.rows({ + argv_row({f.gcc.native(), "-D", "-o", "-c", "unit.cpp"}), + argv_row({f.gcc.native(), "-o", "x.o", "-c", "unit.cpp"}, "unit.cpp", ".", "other.o"), + argv_row({f.gcc.native(), "-o", "x.o", "-o", "y.o", "-c", "unit.cpp"}), + argv_row({f.gcc.native(), "-fsyntax-only", "-o", "x.o", "unit.cpp"}), + argv_row({f.gcc.native(), "-c", "unit.cpp", "-o"})}, pin); + expect(std::ranges::all_of(rejected.contexts, [](const auto &row) { return limited(row); })); +} + +VOID_TEST(CommandImport, unsupported_options_and_different_owning_tu_are_retained) { + Fixture f; + const auto pin = f.pin(); + for (const Strings args : {Strings{f.gcc.native(), "-c", "other.cpp"}, + Strings{f.gcc.native(), "-c", "other.cpp", "unit.cpp"}, + Strings{f.gcc.native(), "-include", "forced.h", "-c", "unit.cpp"}, + Strings{f.gcc.native(), "-include", "-o", "-c", "unit.cpp"}, + Strings{f.gcc.native(), "-fplugin=marker", "-c", "unit.cpp"}, + Strings{f.gcc.native(), "-Xclang", "-load", "-c", "unit.cpp"}, + Strings{f.gcc.native(), "-I=target-root", "-c", "unit.cpp"}, + Strings{f.gcc.native(), "-isystem", "$SYSROOT/inc", "-c", "unit.cpp"}, + Strings{f.gcc.native(), "-I-", "-c", "unit.cpp"}}) { + const auto result = f.rows({argv_row(args)}, pin); + const auto &row = result.contexts.front(); + expect(limited(row) && row.key.owning_tu == f.base / "unit.cpp"); + expect(row.original->arguments == args && !row.sources.front().compiler_path); + } +} + +VOID_TEST(CommandImport, wrong_driver_root_purpose_or_wrapper_never_reads_responses) { + Fixture f; + write_file(f.base / "ok.rsp", "-DFROM_RESPONSE"); + const int watcher = ::inotify_init1(IN_CLOEXEC | IN_NONBLOCK); + require(watcher >= 0); + require(::inotify_add_watch(watcher, (f.base / "ok.rsp").c_str(), IN_ACCESS) >= 0); + pollfd events{watcher, POLLIN, 0}; + const auto checked = f.pin(); + const auto row = argv_row({f.gcc.native(), "@ok.rsp", "-c", "unit.cpp"}); + fs::create_directory(f.temp.path() / "other"); + const auto other = f.pin(Workspace::CompilerDriver::gcc, Workspace::AuthorityLevel::compiler_use, + f.temp.path() / "other"); + const auto purpose = f.pin(Workspace::CompilerDriver::gcc, Workspace::AuthorityLevel::trusted_metadata_refresh); + auto unknown = checked; + unknown.driver = Workspace::CompilerDriver::unknown; + auto wrong_dialect = checked; + wrong_dialect.driver = Workspace::CompilerDriver::clang; + for (const auto &pin : {other, purpose, unknown, wrong_dialect}) { + const auto result = f.rows({row}, pin); + expect(limited(result.contexts.front()) && result.dependencies.empty()); + } + for (const auto &args : {Strings{"g++", "@ok.rsp", "-c", "unit.cpp"}, + Strings{f.clang.native(), "@ok.rsp", "-c", "unit.cpp"}, + Strings{"wrapper", f.gcc.native(), "@ok.rsp", "-c", "unit.cpp"}, + Strings{"ccache", "unselected", "@ok.rsp", f.gcc.native(), "-c", "unit.cpp"}, + Strings{f.gcc.native(), "--rsp-quoting=windows", "@ok.rsp", "-c", "unit.cpp"}}) { + const auto result = f.rows({argv_row(args)}, checked); + expect(limited(result.contexts.front()) && result.dependencies.empty()); + } + expect(f.rows({row}).dependencies.empty()); + expect(::poll(&events, 1, 0) == 0); + const auto ok = f.rows({argv_row({"ccache", f.gcc.native(), "@ok.rsp", "-c", "unit.cpp"})}, checked); + expect(semantic(ok.contexts.front()).front() == f.gcc.native() && ok.dependencies.size() == 1); + expect(::poll(&events, 1, 0) == 1); + ::close(watcher); +} + +VOID_TEST(CommandImport, ambiguous_parent_steps_and_external_routes_stay_passive) { + Fixture f; + fs::create_directory_symlink(f.temp.path(), f.base / "link"); + write_file(f.base / "in.rsp", "-DLOCAL"); + write_file(f.temp.path() / "out.rsp", "-DEXTERNAL"); + const auto pin = f.pin(); + auto result = f.rows({ + argv_row({f.gcc.native(), "@in.rsp", "-c", "unit.cpp"}, "unit.cpp", "link/.."), + argv_row({f.gcc.native(), "@in.rsp", "-c", "unit.cpp"}, "link/../unit.cpp"), + argv_row({f.gcc.native(), "@in.rsp", "-c", "unit.cpp"}, (f.temp.path() / "unit.cpp").native()), + argv_row({f.gcc.native(), "@link/../in.rsp", "-c", "unit.cpp"}), + argv_row({f.gcc.native(), "@" + (f.temp.path() / "out.rsp").native(), "-c", "unit.cpp"}), + argv_row({f.gcc.native(), "-Ilink/../headers", "-c", "unit.cpp"}), + argv_row({f.gcc.native(), "-I", f.temp.path().native(), "-c", "unit.cpp"}), + argv_row({f.gcc.native(), "-o", "link/../x.o", "-c", "unit.cpp"})}, pin); + expect(result.dependencies.empty()); + expect(std::ranges::all_of(result.contexts, [](const auto &row) { return limited(row); })); +} + +VOID_TEST(CommandImport, gcc_and_clang_response_dialects_use_the_invocation_cwd) { + Fixture f; + fs::create_directory(f.base / "sub"); + write_file(f.base / "sub" / "first.rsp", R"('-DSINGLE=a\b' "-DDOUBLE=c\q" @second.rsp)"); + write_file(f.base / "sub" / "second.rsp", "-DWRONG"); + write_file(f.base / "second.rsp", "-I\"include path\" -c 'unit café.cpp'"); + for (auto dialect : {Workspace::CompilerDriver::gcc, Workspace::CompilerDriver::clang}) { + const auto checked = f.pin(dialect); + const auto exe = checked.tool.identity.selected_path.native(); + const auto result = f.rows({argv_row({exe, "@sub/first.rsp"}, "unit café.cpp")}, checked); + const bool gcc = dialect == Workspace::CompilerDriver::gcc; + expect(semantic(result.contexts.front()) == + Strings{exe, gcc ? "-DSINGLE=a\\b" : "-DSINGLE=ab", gcc ? "-DDOUBLE=c\\q" : "-DDOUBLE=cq", + "-I" + (f.base / "include path").native(), "-c", (f.base / "unit café.cpp").native()}); + require(result.dependencies.size() == 2); + expect(result.dependencies[0].logical_path == f.base / "sub/first.rsp" && + result.dependencies[1].logical_path == f.base / "second.rsp"); + } +} + +VOID_TEST(CommandImport, response_cycles_use_active_physical_objects) { + Fixture f; + const auto pin = f.pin(); + const auto row = argv_row({f.gcc.native(), "@one", "-c", "unit.cpp"}); + f.scope.limits.max_response_file_depth = 2; + write_file(f.base / "one", "@one"); + expect(limited(f.rows({row}, pin).contexts.front(), "recursive")); + write_file(f.base / "one", "@two"); + fs::create_hard_link(f.base / "one", f.base / "two"); + const auto aliased = f.rows({row}, pin); + expect(limited(aliased.contexts.front(), "recursive")); + require(aliased.dependencies.size() == 2); + expect(same_provider_object(aliased.dependencies[0], aliased.dependencies[1])); + fs::remove(f.base / "two"); + write_file(f.base / "two", "@one"); + f.scope.limits.max_response_file_depth = 3; + expect(limited(f.rows({row}, pin).contexts.front(), "recursive")); +} + +VOID_TEST(CommandImport, repeated_response_expansions_retain_each_logical_name) { + Fixture f; + const auto checked = f.pin(); + write_file(f.base / "flags", "-DFROM=1"); + fs::create_hard_link(f.base / "flags", f.base / "alias"); + const auto row = argv_row({f.gcc.native(), "@flags", "@alias", "@flags", "-c", "unit.cpp"}); + const auto first = f.rows({row}, checked); + expect(std::ranges::count(semantic(first.contexts.front()), "-DFROM=1"sv) == 3); + require(first.dependencies.size() == 2); + expect(first.dependencies[0].logical_path != first.dependencies[1].logical_path); + write_file(f.base / "replacement", "-DFROM=2"); + fs::rename(f.base / "replacement", f.base / "alias"); + expect(!provider_file_current(f.scope, first.dependencies[1])); + const auto second = f.rows({row}, checked); + expect(first.revision != second.revision); + expect(first.contexts.front().key == second.contexts.front().key); + expect(*first.dependencies[1].bytes == "-DFROM=1"); + expect(std::ranges::count(semantic(second.contexts.front()), "-DFROM=2"sv) == 1); +} + +VOID_TEST(CommandImport, response_depth_bytes_token_and_encoding_limits) { + Fixture f; + const auto pin = f.pin(); + const auto row = argv_row({f.gcc.native(), "@one", "-c", "unit.cpp"}); + write_file(f.base / "one", "@two"); + write_file(f.base / "two", "-DMODE"); + f.scope.limits.max_response_file_depth = 1; + expect(limited(f.rows({row}, pin).contexts.front(), "nesting")); + f.scope.limits.max_response_file_depth = 2; + f.scope.limits.max_response_file_bytes = 9; + expect(limited(f.rows({row}, pin).contexts.front())); + f.scope.limits.max_response_file_bytes = 10; + expect(std::ranges::contains(semantic(f.rows({row}, pin).contexts.front()), "-DMODE"sv)); + write_file(f.base / "one", "@two @two"); + f.scope.limits.max_response_file_bytes = 16; + expect(limited(f.rows({row}, pin).contexts.front(), "byte limit")); + f.scope.limits.max_response_file_bytes = 1024 * 1024; + std::string many; + for (std::size_t i = 0; i < 4096; ++i) + many += "-g "; + write_file(f.base / "one", many); + expect(limited(f.rows({row}, pin).contexts.front(), "argument limit")); + for (const std::string invalid : {std::string{"-D\xff"}, std::string{"x\0y", 3}, + std::string{"'bad"}, std::string{"\xef\xbb\xbf-DNAME"}}) { + write_file(f.base / "one", invalid); + expect(limited(f.rows({row}, pin).contexts.front())); + } + fs::remove(f.base / "one"); + expect(limited(f.rows({row}, pin).contexts.front(), "response file")); +} + +VOID_TEST(CommandImport, oversized_json_argv_and_database_are_rejected_atomically) { + Fixture f; + const auto valid = argv_row({"cc", "-c", "unit.cpp"}); + std::string prefix = "[" + valid + "," + valid.substr(0, valid.size()-1) + ",\"extra\":"; + expect(!f.import(prefix + std::string(32, '[') + "0" + std::string(32, ']') + "}]")); + expect(!f.import(prefix + "\"" + std::string(2 * 1024 * 1024, 'x') + "\"}]")); + std::string dense{"["}; + for (int i = 0; i < 20000; ++i) + dense += "0,"; + expect(!f.import(prefix + dense + "0]}]")); + expect(!f.import("[" + argv_row(Strings(4097, "x")) + "]")); + expect(!f.import("[" + argv_row({std::string(64 * 1024 + 1, 'x')}) + "]")); + write_file(f.database, "[" + valid + "]"); + auto acquired = read_provider_file(f.scope, f.database, FilePurpose::database, f.scope.limits.max_compdb_bytes); + require(acquired.has_value()); + f.scope.limits.max_compdb_bytes = 1; + expect(!import_commands({f.scope, *acquired, {}, {}})); +} + +VOID_TEST(CommandImport, database_must_match_the_current_scope_binding) { + Fixture f; + write_file(f.database, "[]"); + auto file = read_provider_file(f.scope, f.database, FilePurpose::database, 2); + require(file.has_value()); + auto rebound = bind(f.root); + expect(!import_commands({rebound, *file, {}, {}})); + write_file(f.base / "new", "[]"); + fs::rename(f.base / "new", f.database); + auto stale = import_commands({f.scope, *file, {}, {}}); + expect(!stale && stale.error().code == "changed"); +} + +VOID_TEST(CommandImport, physical_owners_follow_links_before_parent_components) { + Fixture f; + for (const auto *name : {"real", "other"}) { + fs::create_directories(f.base / name / "sub"); + write_file(f.base / name / "x.cpp", "int real;\n"); + } + write_file(f.base / "x.cpp", "int innocent;\n"); + fs::create_directory_symlink("real/sub", f.base / "link"); + fs::create_symlink("real/x.cpp", f.base / "alias.cpp"); + const auto linked = argv_row({"c++", "-c", "link/../x.cpp"}, "link/../x.cpp"); + const auto cwd = argv_row({"c++", "-c", "x.cpp"}, "x.cpp", "link/.."); + const auto alias = argv_row({"c++", "-c", "alias.cpp"}, "alias.cpp"); + write_file(f.database, "[" + linked + "," + cwd + "," + alias + "]"); + const auto original = observe_compdb(f.scope, f.database); + require(original.health == ProviderHealth::ready && original.generation); + expect(original.generation->candidates(f.base / "x.cpp").empty()); + expect(original.generation->candidates(f.base / "real/x.cpp").size() == 3); + expect(!changed_provider_input(f.scope, original)); + + fs::remove(f.base / "link"); + fs::create_directory_symlink("other/sub", f.base / "link"); + expect(changed_provider_input(f.scope, original).has_value()); + const auto latest = observe_compdb(f.scope, f.database); + require(latest.health == ProviderHealth::ready && latest.generation); + expect(latest.generation->candidates(f.base / "x.cpp").empty()); + expect(latest.generation->candidates(f.base / "real/x.cpp").size() == 1); + expect(latest.generation->candidates(f.base / "other/x.cpp").size() == 2); + expect(!changed_provider_input(f.scope, latest)); +} + +VOID_TEST(CommandImport, command_and_argv_preserve_a_quoted_literal_backslash) { + Fixture f; + const auto result = f.rows({command_row(f.gcc.native() + R"( -I"inc\q" -c unit.cpp)"), + argv_row({f.gcc.native(), R"(-Iinc\q)", "-c", "unit.cpp"})}, + f.pin()); + const auto &words = semantic(result.contexts.front()); + expect(words == semantic(result.contexts.back())); + expect(std::ranges::contains(words, "-I" + (f.base / R"(inc\q)").native())); +} + +VOID_TEST(CommandImport, creating_a_missing_response_invalidates_the_observation) { + Fixture f; + const auto driver = f.pin(); + write_file(f.database, "[" + argv_row({f.gcc.native(), "@later.rsp", "-c", "unit.cpp"}) + "]"); + const auto missing = observe_compdb(f.scope, f.database, driver); + require(missing.health == ProviderHealth::ready && missing.generation); + expect(limited(missing.generation->contexts().front(), "missing")); + expect(!changed_provider_input(f.scope, missing)); + + const auto response = f.base / "later.rsp"; + write_file(response, "-DFROM_LATER"); + expect(changed_provider_input(f.scope, missing) == response); + const auto present = observe_compdb(f.scope, f.database, driver); + require(present.health == ProviderHealth::ready && present.generation); + expect( + std::ranges::contains(semantic(present.generation->contexts().front()), "-DFROM_LATER"sv)); + expect(present.inputs.size() == 2 && !changed_provider_input(f.scope, present)); + fs::remove(response); + expect(changed_provider_input(f.scope, present) == response); +} + +VOID_TEST(CommandImport, search_directory_authority_follows_the_bound_link_target) { + Fixture f; + const auto driver = f.pin(); + const auto include = f.base / "include-alias"; + fs::create_directories(f.temp.path() / "outside"); + fs::create_directory_symlink(f.temp.path() / "outside", include); + write_file(f.database, + "[" + argv_row({f.gcc.native(), "-Iinclude-alias", "-c", "unit.cpp"}) + "]"); + const auto external = observe_compdb(f.scope, f.database, driver); + require(external.health == ProviderHealth::ready && external.generation); + expect(limited(external.generation->contexts().front())); + expect(!changed_provider_input(f.scope, external)); + fs::create_directory(f.base / "inside"); + fs::remove(include); + fs::create_directory_symlink("inside", include); + expect(changed_provider_input(f.scope, external) == include); + const auto internal = observe_compdb(f.scope, f.database, driver); + require(internal.health == ProviderHealth::ready && internal.generation); + expect(std::ranges::contains(semantic(internal.generation->contexts().front()), + "-I" + include.native())); + expect(!changed_provider_input(f.scope, internal)); +} + +VOID_TEST(CommandImport, bounded_response_names_apply_across_the_whole_generation) { + Fixture f; + const auto checked = f.pin(); + std::string rows = "[" + argv_row({f.gcc.native(), "-c", "unit.cpp"}); + for (unsigned i = 0; i < 256; ++i) { + rows += "," + argv_row({f.gcc.native(), "@missing-" + std::to_string(i), "-c", "unit.cpp"}); + } + auto within = f.import(rows + "]", checked); + require(within.has_value()); + expect(within->contexts.size() == 257 && within->contexts.front().semantic_arguments && + limited(within->contexts.back(), "missing")); + const auto repeated = argv_row({f.gcc.native(), "@missing-0", "-c", "unit.cpp"}); + auto reuse = f.import(rows + "," + repeated + "]", checked); + expect(reuse && reuse->contexts.size() == 258); + const auto extra = argv_row({f.gcc.native(), "@extra", "-c", "unit.cpp"}); + expect(!f.import(rows + "," + extra + "]", checked)); +} diff --git a/tests/providers/CompdbProviderTests.cpp b/tests/providers/CompdbProviderTests.cpp new file mode 100644 index 0000000..ba004fc --- /dev/null +++ b/tests/providers/CompdbProviderTests.cpp @@ -0,0 +1,39 @@ +#include "ProviderFixture.hpp" +#include + +namespace { +using namespace provider_test; +using namespace provider_test::Build; +using Void::Testing::expect; +using Void::Testing::require; + +VOID_TEST(CompdbProvider, passive_database_survives_atomic_replacement_and_keeps_old_generation) { + Fixture f; + f.bind(); + write_json(f.compdb, Json{f.rows()}); + auto first = observe_compdb(f.scope, f.compdb); + require(first.generation != nullptr); + expect(first.health == ProviderHealth::ready && + first.generation->candidates(f.source).size() == 2); + auto temporary = f.root / "next.json"; + write_json(temporary, Json{Json::Array{}}); + fs::rename(temporary, f.compdb); + auto second = observe_compdb(f.scope, f.compdb); + require(second.generation != nullptr); + expect(second.generation->contexts().empty()); + expect(first.generation->identity().revision != second.generation->identity().revision); + expect(!provider_file_current(f.scope, first.inputs.front())); + expect(first.generation->contexts().size() == 2); +} + +VOID_TEST(CompdbProvider, invalid_or_deleted_databases_produce_distinct_status) { + Fixture f; + f.bind(); + write_bytes(f.compdb, "[{"); + auto invalid = observe_compdb(f.scope, f.compdb); + expect(invalid.health == ProviderHealth::invalid && !invalid.generation); + fs::remove(f.compdb); + auto missing = observe_compdb(f.scope, f.compdb); + expect(missing.health == ProviderHealth::missing && !missing.generation); +} +} // namespace diff --git a/tests/providers/ModelTests.cpp b/tests/providers/ModelTests.cpp new file mode 100644 index 0000000..c3682bb --- /dev/null +++ b/tests/providers/ModelTests.cpp @@ -0,0 +1,642 @@ +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +namespace Docs = Void::LanguageServer::Documents; +using namespace Void::LanguageServer::Build; +using Void::Testing::expect; +using Void::Testing::require; + +template T take(std::expected value) { + require(value.has_value()); + return std::move(*value); +} + +void write(const fs::path &path, std::string_view content) { + std::ofstream output(path, std::ios::binary); + output << content; + output.close(); + require(output.good()); +} + +struct Fixture { + Void::FileSystem::TempDir directory{"vls_build_model_"}; + const fs::path root{fs::canonical(directory.path())}; + const fs::path header{root / "api.hpp"}, source{root / "main.cpp"}, other{root / "other.cpp"}, + module{root / "core.cppm"}; + WorkspaceIdentity workspace{root, "editor-session"}; + Docs::DocumentStore documents; + SelectionState selection{workspace, header}; + + Fixture() { + write(header, "int api();"); + write(source, "#include \"api.hpp\""); + write(other, "#include \"api.hpp\"\nimport core;"); + write(module, "export module core;"); + } + + BuildContext record(std::string profile = "debug", std::string target = "app", + fs::path tu = {}) const { + if (tu.empty()) { + tu = source; + } + auto argv = std::vector{"g++", "-DNAME=" + target, tu.string()}; + return { + .key = {profile, target, ContextRole::target, "main-command", tu}, + .source_language = "c++", + .original = OriginalCommand{root / "commands.json", "record-" + target, argv, {}, {}}, + .semantic_arguments = argv, + .working_directory = root, + .toolchain = "gcc-16/toolchain-inputs", + .standard_library = "libstdc++/inputs", + .environment = "selected-environment", + .sources = {{tu, tu, SourceOrigin::workspace, Editability::editable, "source-record"}, + {header, header, SourceOrigin::workspace, Editability::editable, + "include-record"}}, + .prerequisites = std::vector{}, + .artifacts = std::vector{}, + .limitations = {}}; + } + + Generation generation(std::vector records, + std::string revision = "provider-revision", + std::shared_ptr lease = {}) const { + return take(BuildGeneration::create({workspace, "fixture-provider", std::move(revision)}, + std::move(records), std::move(lease))); + } + Selection select() { return take(selection.update(generation({record()}))); } + Snapshot read(const fs::path &path) { return take(documents.resolve_content(path)); } + AnalysisInputs inputs(const Selection &selected) { + return {.document = read(selected->scope->file), + .translation_unit = + selected->selected ? read(selected->selected->key.owning_tu) : Snapshot{}, + .dependencies = std::vector{}, + .lookup_epoch = 10, + .configuration_generation = 20, + .trust_generation = 30, + .backend = BackendIdentity{"fixture", "v3", "worker-v1"}, + .rename = {}}; + } + FileOverride override_for(const ContextKey &key) const { + return {root, header, "fixture-provider", key}; + } + RenameCoverage coverage(const Selection &selected) const { + std::vector checked; + for (const auto *candidate : selected->alternatives()) { + checked.push_back({selected->generation, candidate->key, "verified-input-closure"}); + } + return {{root}, std::move(checked), "verified-edit-locations"}; + } +}; + +Revision capture(const Selection &selection, AnalysisInputs inputs) { + return take(AnalysisRevision::capture(selection, std::move(inputs))); +} + +bool mentions(const Readiness &readiness, InputIssue issue) { + return std::ranges::contains(readiness.issues, issue); +} + +VOID_TEST(BuildModel, selection_preserves_conflicting_commands_and_follows_precedence) { + Fixture f; + auto app = f.record(); + auto tests = f.record("release", "tests"); + auto generation = f.generation({tests, app}); + SelectionState source_selection{f.workspace, f.source}; + expect(take(source_selection.update(generation))->alternatives().size() == 2); + auto fallback = take(f.selection.update(generation)); + require(fallback->alternatives().size() == 2 && fallback->selected); + expect(fallback->reason == SelectionReason::fallback && fallback->selected->key == app.key); + expect(fallback->alternatives()[0]->semantic_arguments != + fallback->alternatives()[1]->semantic_arguments); + + EditorSelection editor{f.root, generation->identity().provider, "release", "tests", {}, {}}; + auto chosen = take(f.selection.update(generation, {}, editor)); + expect(chosen->reason == SelectionReason::editor && chosen->selected->key == tests.key); + auto overridden = take(f.selection.update(generation, f.override_for(app.key), editor)); + expect(overridden->reason == SelectionReason::file_override && + overridden->selected->key == app.key); + expect(overridden == take(f.selection.update(generation, f.override_for(app.key), editor))); + auto cleared = take(f.selection.update(generation, {}, editor)); + expect(cleared->selected->key == tests.key && cleared->revision > overridden->revision); +} + +VOID_TEST(BuildModel, missing_override_is_retained_until_cleared_or_resolved) { + Fixture f; + auto old = f.record(); + auto remaining = f.record("release", "other"); + auto key = f.override_for(old.key); + auto generation = f.generation({remaining}); + EditorSelection editor{f.root, "fixture-provider", "release", {}, {}, {}}; + auto missing = take(f.selection.update(generation, key, editor)); + expect(missing->reason == SelectionReason::missing_override && !missing->selected); + expect(missing->file_override == key && missing->alternatives().size() == 1); + auto missing_inputs = capture(missing, f.inputs(missing)); + expect(mentions(missing_inputs->readiness(Operation::status), InputIssue::context)); + expect(missing_inputs->readiness(Operation::diagnostics).level == ReadinessLevel::unavailable); + auto restored = take(f.selection.update(f.generation({old, remaining}), key, editor)); + expect(restored->selected->key == old.key); + key.provider = "a-different-provider"; + expect(take(f.selection.update(generation, key))->reason == SelectionReason::missing_override); + auto cleared = take(f.selection.update(generation, {}, editor)); + expect(cleared->reason == SelectionReason::editor && !cleared->file_override); + SelectionState unowned{f.workspace, f.root / "absent.hpp"}; + auto absent = take(unowned.update(generation)); + expect(absent->reason == SelectionReason::no_owner && absent->alternatives().empty()); +} + +VOID_TEST(BuildModel, fallback_is_order_independent_and_keeps_host_and_tu_roles) { + Fixture f; + auto app = f.record(); + auto host = app; + host.key.role = ContextRole::host_description; + auto other = f.record("debug", "app", f.other); + auto first = take(f.selection.update(f.generation({host, other, app}))); + auto second = take(f.selection.update(f.generation({app, other, host}))); + require(first->alternatives().size() == 3 && second->alternatives().size() == 3); + for (std::size_t i = 0; i < 3; ++i) { + expect(first->alternatives()[i]->key == second->alternatives()[i]->key); + } + expect(first->selected->key == second->selected->key); + auto selected_host = take(f.selection.update(second->generation, f.override_for(host.key))); + auto selected_other = take(f.selection.update(second->generation, f.override_for(other.key))); + expect(selected_host->selected->key.role == ContextRole::host_description); + auto revision = capture(selected_other, f.inputs(selected_other)); + expect(revision->inputs.document->identity.canonical_path == f.header); + expect(revision->inputs.translation_unit->identity.canonical_path == f.other); + expect(revision->selection->selected->source_language == "c++"); +} + +VOID_TEST(BuildModel, invalid_keys_mappings_and_foreign_scopes_are_rejected) { + Fixture f; + const GenerationIdentity id{f.workspace, "fixture-provider", "r1"}; + auto ctx = f.record(); + expect(BuildGeneration::create(id, {ctx, ctx}) == + std::unexpected{ModelError::duplicate_context}); + auto invalid = ctx; + invalid.key.alternative.clear(); + expect(BuildGeneration::create(id, {invalid}) == std::unexpected{ModelError::invalid_context}); + invalid = ctx; + invalid.sources.push_back(invalid.sources.front()); + expect(BuildGeneration::create(id, {invalid}) == std::unexpected{ModelError::invalid_mapping}); + invalid = ctx; + invalid.sources.erase(invalid.sources.begin()); + expect(BuildGeneration::create(id, {invalid}) == std::unexpected{ModelError::invalid_mapping}); + invalid = ctx; + invalid.sources.back().source_path = f.root.string() + "-unrelated/api.hpp"; + expect(BuildGeneration::create(id, {invalid}) == std::unexpected{ModelError::invalid_mapping}); + auto generation = f.generation({ctx}); + auto key = f.override_for(ctx.key); + key.file = f.other; + expect(f.selection.update(generation, key) == std::unexpected{ModelError::wrong_scope}); + SelectionState other_session{{f.root, "another-session"}, f.header}; + expect(other_session.update(generation) == std::unexpected{ModelError::wrong_scope}); + auto bad_root = id; + bad_root.workspace.root = "relative"; + expect(BuildGeneration::create(bad_root, {ctx}) == + std::unexpected{ModelError::invalid_identity}); +} + +VOID_TEST(BuildModel, argv_boundaries_original_command_and_unknown_fields_survive) { + Fixture f; + auto a = f.record(); + a.key.profile.reset(); + a.key.target.reset(); + a.original->arguments = {"gcc", "-DX=a b", "-Iinc", "-Iinc", ""}; + a.original->command = "gcc '-DX=a b' -Iinc -Iinc ''"; + a.original->original_record = "{opaque provider extension}"; + a.semantic_arguments = {"/tool/gcc", "-DX=a b", "-I/selected/inc", "-I/selected/inc", ""}; + auto b = a; + b.key.alternative = "other-command"; + b.original->arguments = {"gcc", "-DX=a", "b", "-Iinc", "-Iinc", ""}; + b.semantic_arguments = {"/tool/gcc", "-DX=a", "b", "-I/selected/inc", "-I/selected/inc", ""}; + b.artifacts.reset(); + auto generation = f.generation({b, a}); + const auto *left = generation->find(a.key); + const auto *right = generation->find(b.key); + require(left && right && left != right); + expect(left->original->arguments == a.original->arguments && + left->original->command == a.original->command); + expect(left->original->original_record == a.original->original_record); + expect(left->semantic_arguments == a.semantic_arguments && + left->semantic_arguments != right->semantic_arguments); + expect(!left->key.target && !left->key.profile && left->artifacts->empty() && + !right->artifacts); + std::vector supplied{a}; + auto &provider_argv = *supplied.front().semantic_arguments; + auto frozen = take(BuildGeneration::create(generation->identity(), std::move(supplied))); + provider_argv.clear(); + expect(frozen->contexts().front().semantic_arguments == a.semantic_arguments); +} + +VOID_TEST(BuildModel, identical_disk_rereads_complete_and_changed_bytes_invalidate) { + Fixture f; + auto selected = f.select(); + auto first = capture(selected, f.inputs(selected)); + PublicationSlot slot{f.selection, Operation::semantic}; + require(slot.replace_inputs(1, first).has_value()); + auto ticket = take(slot.issue()); + auto reread = capture(selected, f.inputs(selected)); + expect(first->inputs.document->revision_id != reread->inputs.document->revision_id); + expect(first->same_input_as(*reread)); + require(slot.replace_inputs(2, reread).has_value()); + std::string payload(64, 'x'); + payload[32] = '\0'; + const auto expected = payload; + char *worker_buffer = payload.data(); + require(slot.publish(ticket, std::move(payload))); + worker_buffer[0] = 'y'; + auto historical = slot.current(); + require(historical && historical->payload == expected); + auto next = take(slot.issue()); + write(f.header, "int api(long);"); + auto changed = capture(selected, f.inputs(selected)); + expect(!reread->same_input_as(*changed)); + require(slot.replace_inputs(3, changed).has_value()); + expect(!slot.current() && !slot.publish(next, "obsolete") && historical->payload == expected); +} + +VOID_TEST(BuildModel, same_text_overlay_reopen_and_changed_owning_tu_reject_old_work) { + Fixture f; + auto selected = f.select(); + const auto uri = Docs::path_to_file_uri(f.header); + auto first_open = take(f.documents.open(uri, "cpp", 1, "int api();")); + auto inputs = f.inputs(selected); + require(inputs.document == first_open); + auto first = capture(selected, inputs); + PublicationSlot slot{f.selection, Operation::diagnostics}; + require(slot.replace_inputs(1, first).has_value()); + auto old = take(slot.issue()); + require(f.documents.close(uri).has_value()); + inputs.document = take(f.documents.open(uri, "cpp", 1, "int api();")); + auto reopened = capture(selected, inputs); + expect(inputs.document->text == first_open->text && + inputs.document->version == first_open->version); + expect(!first->same_input_as(*reopened)); + require(slot.replace_inputs(2, reopened).has_value()); + expect(!slot.publish(old, "obsolete incarnation")); + auto for_old_tu = take(slot.issue()); + write(f.source, "#define REDIRECT\n#include \"api.hpp\""); + inputs.translation_unit = f.read(f.source); + require(slot.replace_inputs(3, capture(selected, inputs)).has_value()); + expect(!slot.publish(for_old_tu, "obsolete translation unit")); +} + +VOID_TEST(BuildModel, negative_lookup_and_ordered_import_inputs_invalidate) { + Fixture f; + auto selected = f.select(); + auto inputs = f.inputs(selected); + inputs.dependencies->push_back({DependencyKind::import, "core", f.module, f.read(f.module)}); + inputs.dependencies->push_back({DependencyKind::include, "api.hpp", f.header, inputs.document}); + auto initial = capture(selected, inputs); + auto observed = inputs; + auto &producer_name = observed.dependencies->front().name; + auto frozen = take(AnalysisRevision::capture(selected, std::move(observed))); + producer_name = "other"; + expect(frozen->inputs.dependencies->front().name == "core"); + PublicationSlot slot{f.selection, Operation::semantic}; + require(slot.replace_inputs(1, initial).has_value()); + auto old = take(slot.issue()); + const auto higher_priority = f.root / "earlier"; + fs::create_directory(higher_priority); + require(!fs::exists(higher_priority / "api.hpp")); + write(higher_priority / "api.hpp", "int different_api();"); + // The owner observed creation on an earlier search root; all former positive inputs still + // match. + ++*inputs.lookup_epoch; + auto shadowed = capture(selected, inputs); + require(slot.replace_inputs(2, shadowed).has_value()); + expect(!slot.publish(old, "obsolete search")); + std::ranges::reverse(*inputs.dependencies); + auto reordered = capture(selected, inputs); + expect(!shadowed->same_input_as(*reordered)); + auto &import = inputs.dependencies->back(); + import.name = "core:partition"; + auto renamed = capture(selected, inputs); + expect(!renamed->same_input_as(*reordered)); + write(f.module, "export module core;\nexport int n;"); + import.source = f.read(f.module); + expect(!renamed->same_input_as(*capture(selected, inputs))); +} + +VOID_TEST(BuildModel, mapping_environment_language_and_backend_identify_revisions) { + Fixture f; + auto ctx = f.record(); + auto first_selection = take(f.selection.update(f.generation({ctx}))); + auto inputs = f.inputs(first_selection); + auto first = capture(first_selection, inputs); + auto change = [&](BuildContext next) { + auto selected = take(f.selection.update(f.generation({next}))); + expect(selected->generation->identity().revision == + first_selection->generation->identity().revision); + expect(!first->same_input_as(*capture(selected, inputs))); + return selected; + }; + auto mapped = ctx; + mapped.sources.back().compiler_path = f.root / "generated" / "api.hpp"; + auto mapped_selection = change(mapped); + expect(mapped_selection->selected->mapping_for(f.header)->compiler_path == + mapped.sources.back().compiler_path); + auto env = ctx; + env.environment = "changed-environment"; + expect(change(env)->selected->environment == env.environment); + auto language = ctx; + language.source_language = "c"; + expect(change(language)->selected->source_language == language.source_language); + auto backend = inputs; + backend.backend->protocol = "worker-v2"; + expect(!first->same_input_as(*capture(first_selection, backend))); + backend = inputs; + backend.backend->version = "different-build"; + expect(!first->same_input_as(*capture(first_selection, backend))); +} + +VOID_TEST(BuildModel, mismatched_source_owner_and_inconsistent_dependency_fail_capture) { + Fixture f; + auto selected = f.select(); + auto inputs = f.inputs(selected); + auto wrong = inputs; + wrong.document = f.read(f.source); + expect(AnalysisRevision::capture(selected, wrong) == std::unexpected{ModelError::wrong_scope}); + wrong = inputs; + wrong.translation_unit = f.read(f.other); + expect(AnalysisRevision::capture(selected, wrong) == std::unexpected{ModelError::wrong_scope}); + write(f.header, "int changed;"); + inputs.dependencies->push_back( + {DependencyKind::include, "api.hpp", f.header, f.read(f.header)}); + expect(AnalysisRevision::capture(selected, inputs) == + std::unexpected{ModelError::invalid_input}); + auto other_inputs = f.inputs(selected); + other_inputs.backend->version.clear(); + expect(AnalysisRevision::capture(selected, other_inputs) == + std::unexpected{ModelError::invalid_identity}); +} + +VOID_TEST(BuildModel, partial_metadata_allows_evidenced_diagnostics_and_status) { + Fixture f; + auto ctx = f.record(); + ctx.environment.reset(); + ctx.prerequisites = std::vector{{"module", {}, Availability::missing}}; + ctx.artifacts.reset(); + ctx.limitations.push_back("unsupported driver operand"); + auto selected = take(f.selection.update(f.generation({ctx}))); + auto inputs = f.inputs(selected); + inputs.lookup_epoch.reset(); + inputs.dependencies.reset(); + auto revision = capture(selected, inputs); + for (auto operation : {Operation::status, Operation::diagnostics}) { + const auto &readiness = revision->readiness(operation); + expect(readiness.level == ReadinessLevel::degraded); + expect(mentions(readiness, InputIssue::prerequisites) && + mentions(readiness, InputIssue::lookup_coverage)); + PublicationSlot slot{f.selection, operation}; + require(slot.replace_inputs(1, revision).has_value()); + expect(slot.publish(take(slot.issue()), "partial")); + } + for (auto operation : {Operation::semantic, Operation::rename}) { + PublicationSlot slot{f.selection, operation}; + require(slot.replace_inputs(1, revision).has_value()); + expect(slot.issue() == std::unexpected{ModelError::operation_unavailable}); + } + inputs.translation_unit.reset(); + expect(capture(selected, inputs)->readiness(Operation::diagnostics).level == + ReadinessLevel::unavailable); +} + +VOID_TEST(BuildModel, rename_requires_all_affected_contexts_and_editable_origins) { + Fixture f; + auto generation = f.generation({f.record(), f.record("release", "tests", f.other)}); + auto selected = take(f.selection.update(generation)); + auto inputs = f.inputs(selected); + auto revision = capture(selected, inputs); + expect(revision->readiness(Operation::semantic).level == ReadinessLevel::ready); + expect(revision->readiness(Operation::rename).level == ReadinessLevel::unavailable); + inputs.rename = f.coverage(selected); + auto full = capture(selected, inputs); + expect(full->readiness(Operation::rename).level == ReadinessLevel::ready); + PublicationSlot slot{f.selection, Operation::rename}; + require(slot.replace_inputs(1, full).has_value()); + auto pending = take(slot.issue()); + auto partial = inputs; + partial.rename->contexts->pop_back(); + auto missing = capture(selected, partial); + expect(mentions(missing->readiness(Operation::rename), InputIssue::affected_contexts)); + require(slot.replace_inputs(2, missing).has_value()); + expect(!slot.publish(pending, "obsolete complete proof") && !slot.issue().has_value()); + partial = inputs; + partial.rename->contexts->back().verification.reset(); + expect(capture(selected, partial)->readiness(Operation::rename).level == + ReadinessLevel::unavailable); + partial = inputs; + partial.rename->editable_spelling_proof.reset(); + expect(mentions(capture(selected, partial)->readiness(Operation::rename), + InputIssue::edit_provenance)); + auto read_only = f.record(); + read_only.sources.back().editability = Editability::read_only; + selected = take(f.selection.update(f.generation({read_only}))); + inputs.rename = f.coverage(selected); + expect(capture(selected, inputs)->readiness(Operation::rename).level == + ReadinessLevel::unavailable); + auto inactive = f.record("release", "tests", f.other); + inactive.prerequisites.reset(); + selected = take(f.selection.update(f.generation({f.record(), inactive}))); + inputs.rename = f.coverage(selected); + auto incomplete = capture(selected, inputs); + expect(incomplete->readiness(Operation::semantic).level == ReadinessLevel::ready); + expect(mentions(incomplete->readiness(Operation::rename), InputIssue::affected_contexts)); +} + +VOID_TEST(BuildModel, cross_root_rename_proofs_bind_declared_roots_sessions_and_generations) { + Fixture f, sibling; + auto selected = f.select(); + auto inputs = f.inputs(selected); + inputs.rename = f.coverage(selected); + auto other = sibling.generation({sibling.record()}); + inputs.rename->contexts->push_back({other, other->contexts().front().key, "sibling-checked"}); + expect(AnalysisRevision::capture(selected, inputs) == std::unexpected{ModelError::wrong_scope}); + inputs.rename->workspace_roots.push_back(sibling.root); + auto revision = capture(selected, inputs); + expect(revision->readiness(Operation::rename).level == ReadinessLevel::ready); + PublicationSlot slot{f.selection, Operation::rename}; + require(slot.replace_inputs(1, revision).has_value()); + auto ticket = take(slot.issue()); + // The session owner invalidates the proof when its sibling workspace changes. + require(slot.replace_inputs(2, {}).has_value()); + expect(!slot.publish(ticket, "obsolete sibling evidence")); + sibling.workspace.session = "foreign-session"; + inputs.rename->contexts->back().generation = sibling.generation({sibling.record()}); + expect(AnalysisRevision::capture(selected, inputs) == std::unexpected{ModelError::wrong_scope}); + inputs.rename = f.coverage(selected); + auto repeated = inputs.rename->contexts->front(); + inputs.rename->contexts->push_back(repeated); + expect(AnalysisRevision::capture(selected, inputs) == + std::unexpected{ModelError::invalid_input}); + inputs.rename->contexts->back().generation = f.generation({f.record()}); + expect(AnalysisRevision::capture(selected, inputs) == + std::unexpected{ModelError::invalid_input}); +} + +VOID_TEST(BuildModel, retained_generation_owns_artifacts_until_the_last_ticket_releases) { + Fixture f; + auto ctx = f.record(); + ctx.artifacts = + std::vector{{f.root / "core.bmi", "immutable-bmi", Availability::ready}}; + auto unretained = take(f.selection.update(f.generation({ctx}))); + expect(mentions(capture(unretained, f.inputs(unretained))->readiness(Operation::semantic), + InputIssue::artifacts)); + PublicationSlot slot{f.selection, Operation::semantic}; + std::weak_ptr old_lease; + std::weak_ptr old_generation; + Ticket outstanding; + { + auto lease = std::make_shared(); + auto generation = f.generation({ctx}, "retained", lease); + old_lease = lease; + old_generation = generation; + auto selected = take(f.selection.update(generation)); + auto revision = capture(selected, f.inputs(selected)); + require(slot.replace_inputs(1, revision).has_value()); + outstanding = take(slot.issue()); + } + auto fresh = f.select(); + require(slot.replace_inputs(2, capture(fresh, f.inputs(fresh))).has_value()); + expect(!old_lease.expired() && !old_generation.expired()); + expect(!slot.publish(outstanding, "superseded") && + outstanding->revision->selection->generation->retains_artifacts()); + outstanding.reset(); + expect(old_lease.expired() && old_generation.expired()); + + struct ObservedLease final : ArtifactLease { + ObservedLease(PublicationSlot &slot, bool &released) : slot(slot), released(released) {} + ~ObservedLease() override { released = !slot.current(); } + PublicationSlot &slot; + bool &released; + }; + bool released = false; + { + auto lease = std::make_shared(slot, released); + auto selected = take(f.selection.update(f.generation({ctx}, "observed", lease))); + require(slot.replace_inputs(3, capture(selected, f.inputs(selected))).has_value()); + require(slot.publish(take(slot.issue()), "retained")); + } + (void)f.select(); + require(slot.replace_inputs(4, {}).has_value()); + expect(released); +} + +VOID_TEST(BuildModel, selection_aba_and_reordered_observations_cannot_resurrect_results) { + Fixture f; + auto a = f.record(); + auto b = f.record("release", "tests"); + auto generation = f.generation({a, b}); + auto first = take(f.selection.update(generation, f.override_for(a.key))); + auto inputs = f.inputs(first); + auto initial = capture(first, inputs); + PublicationSlot slot{f.selection, Operation::semantic}; + require(slot.replace_inputs(1, initial).has_value()); + auto obsolete = take(slot.issue()); + auto second = take(f.selection.update(generation, f.override_for(b.key))); + require(slot.replace_inputs(2, capture(second, inputs)).has_value()); + require(slot.publish(take(slot.issue()), "B")); + auto again = take(f.selection.update(generation, f.override_for(a.key))); + expect(first->selected == again->selected && first->revision < second->revision && + second->revision < again->revision); + require(slot.replace_inputs(3, capture(again, inputs)).has_value()); + expect(!slot.current() && !slot.publish(obsolete, "obsolete A")); + auto newest = take(slot.issue()); + expect(slot.replace_inputs(2, {}) == std::unexpected{ModelError::superseded}); + expect(slot.publish(newest, "current A")); + expect(slot.replace_inputs(4, initial) == std::unexpected{ModelError::superseded}); + expect(!slot.current()); +} + +VOID_TEST(BuildModel, overlapping_requests_cancel_replay_and_retire_without_history) { + Fixture f; + auto selected = f.select(); + auto revision = capture(selected, f.inputs(selected)); + PublicationSlot slot{f.selection, Operation::diagnostics}, + other{f.selection, Operation::diagnostics}; + require(slot.replace_inputs(1, revision).has_value() && + other.replace_inputs(1, revision).has_value()); + auto older = take(slot.issue()); + auto foreign = take(other.issue()); + expect(older->id == foreign->id && !slot.publish(foreign, "foreign")); + auto latest = take(slot.issue()); + expect(!slot.cancel(older)); + require(slot.publish(latest, "latest")); + expect(!slot.publish(older, "older") && !slot.publish(latest, "replayed")); + expect(slot.current()->payload == "latest"); + std::weak_ptr previous; + for (int i = 0; i < 128; ++i) { + auto pending = take(slot.issue()); + expect(previous.expired()); + previous = pending; + } + auto cancelled = previous.lock(); + require(cancelled && slot.cancel(cancelled)); + expect(!slot.publish(cancelled, "cancelled") && !slot.cancel(cancelled)); + cancelled.reset(); + expect(previous.expired()); + require(slot.replace_inputs(2, {}).has_value()); + expect(!slot.current() && slot.issue() == std::unexpected{ModelError::no_inputs}); +} + +VOID_TEST(BuildModel, revocation_and_configuration_floors_survive_empty_state) { + Fixture f; + auto selected = f.select(); + auto inputs = f.inputs(selected); + auto old = capture(selected, inputs); + PublicationSlot slot{f.selection, Operation::semantic}; + require(slot.replace_inputs(1, old).has_value()); + require(slot.publish(take(slot.issue()), "initial")); + auto pending = take(slot.issue()); + slot.revoke_trust({f.root, "other-session"}, 31); + expect(slot.current() != nullptr); + slot.revoke_trust(f.workspace, 31); + expect(!slot.current() && !slot.publish(pending, "revoked")); + expect(slot.replace_inputs(2, old) == std::unexpected{ModelError::superseded}); + inputs.trust_generation = 31; + inputs.configuration_generation = 21; + auto fresh = capture(selected, inputs); + require(slot.replace_inputs(3, fresh).has_value()); + auto current = take(slot.issue()); + slot.revoke_trust(f.workspace, 30); + expect(slot.publish(current, "fresh")); + require(slot.replace_inputs(4, {}).has_value()); + inputs.configuration_generation = 20; + expect(slot.replace_inputs(5, capture(selected, inputs)) == + std::unexpected{ModelError::superseded}); + expect(slot.issue() == std::unexpected{ModelError::no_inputs}); +} + +VOID_TEST(BuildModel, racing_revocation_and_completion_leave_no_stale_publication) { + Fixture f; + auto selected = f.select(); + auto inputs = f.inputs(selected); + PublicationSlot slot{f.selection, Operation::semantic}; + for (std::uint64_t step = 1; step <= 24; ++step) { + inputs.trust_generation = step; + require(slot.replace_inputs(step, capture(selected, inputs)).has_value()); + auto ticket = take(slot.issue()); + std::barrier start{2}; + std::jthread worker{[&] { + start.arrive_and_wait(); + (void)slot.publish(ticket, "result"); + }}; + start.arrive_and_wait(); + slot.revoke_trust(f.workspace, step + 1); + worker.join(); + expect(!slot.current() && !slot.publish(ticket, "late") && !slot.issue().has_value()); + } +} +} // namespace diff --git a/tests/providers/ProviderFileTests.cpp b/tests/providers/ProviderFileTests.cpp new file mode 100644 index 0000000..ead557b --- /dev/null +++ b/tests/providers/ProviderFileTests.cpp @@ -0,0 +1,202 @@ +#include +#include +#include +#include + +#include +#include + +namespace { +namespace fs = std::filesystem; +using namespace Void::LanguageServer::Build; +using Void::Testing::expect; +using Void::Testing::require; + +struct Files { + Void::FileSystem::TempDir directory{"vls_provider_files_"}; + const fs::path root = fs::canonical(directory.path()) / "workspace"; + const fs::path other = root.parent_path() / "external"; + ProviderScope scope{.workspace = {root, "one"}}; + Files() { + fs::create_directories(root); + fs::create_directories(other); + } + void bind() { + auto bound = bind_provider_scope(scope); + require(bound.has_value()); + scope = std::move(*bound); + } + static void write(const fs::path &path, std::string_view bytes) { + fs::create_directories(path.parent_path()); + std::ofstream file{path, std::ios::binary}; + file << bytes; + file.close(); + require(file.good()); + } + auto read(const fs::path &path, FilePurpose purpose = FilePurpose::database, + std::size_t limit = 1024) const { + return read_provider_file(scope, path, purpose, limit); + } +}; +} // namespace + +VOID_TEST(ProviderFiles, hashes_and_revalidates_a_stable_regular_file) { + Files f; + f.bind(); + auto path = f.root / "compile_commands.json"; + Files::write(path, "abc"); + auto captured = f.read(path); + require(captured.has_value()); + expect(*captured->bytes == "abc"); + expect(captured->content_id == + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + expect(captured->logical_path == path && captured->canonical_path == path); + Files::write(f.root / "unrelated", "data"); + expect(provider_file_current(f.scope, *captured)); + Files::write(path, "abcd"); + expect(!provider_file_current(f.scope, *captured)); + expect(*captured->bytes == "abc"); +} + +VOID_TEST(ProviderFiles, root_pins_survive_as_identifiers_and_reject_replacement) { + Files f; + auto path = f.other / "selected.json"; + f.scope.exact_database = path; + f.bind(); + fs::rename(f.other, f.other.string() + "-old"); + Files::write(path, "new"); + auto result = f.read(path); + require(!result); + expect(result.error().code == "changed"); + fs::rename(f.root, f.root.string() + "-old"); + Files::write(f.root / "x", "x"); + auto replaced = f.read(f.root / "x"); + require(!replaced); + expect(replaced.error().code == "changed"); +} + +VOID_TEST(ProviderFiles, new_incarnation_keeps_the_granted_directories_and_retires_old_evidence) { + Files f; + const auto db = f.other / "selected.json"; + f.scope.exact_database = db; + f.bind(); + Files::write(db, "original"); + const auto first = f.read(db); + require(first.has_value()); + + auto second = reuse_provider_scope(f.scope, "two"); + require(second.has_value()); + auto next = read_provider_file(*second, db, FilePurpose::database, 1024); + require(next.has_value()); + expect(same_provider_object(*first, *next)); + expect(!provider_file_current(*second, *first)); + + fs::rename(f.other, f.other.string() + "-first"); + Files::write(db, "replacement"); + expect(!provider_file_current(*second, *next)); + auto third = reuse_provider_scope(f.scope, "three"); + require(third.has_value()); + auto replaced = read_provider_file(*third, db, FilePurpose::database, 1024); + require(!replaced); + expect(replaced.error().code == "changed"); + Files::write(f.root / "inside", "valid"); + expect(read_provider_file(*third, f.root / "inside", FilePurpose::database, 1024).has_value()); +} + +VOID_TEST(ProviderFiles, external_file_grants_are_exact_and_purpose_bound) { + Files f; + const auto db = f.other / "compile_commands.json", neighbor = f.other / "flags.rsp"; + f.scope.exact_database = db; + f.bind(); + Files::write(db, "[]"); + Files::write(neighbor, "-DOUTSIDE"); + require(f.read(db).has_value()); + expect(!f.read(db, FilePurpose::selection)); + expect(!f.read(neighbor)); + expect(!f.read(neighbor, FilePurpose::response)); + auto tampered = f.scope; + tampered.exact_database = neighbor; + expect(!read_provider_file(tampered, neighbor, FilePurpose::database, 1024)); + fs::remove(db); + fs::create_symlink(neighbor, db); + expect(!f.read(db)); +} + +VOID_TEST(ProviderFiles, native_build_roots_admit_only_editor_metadata_shapes) { + Files f; + f.scope.build_root = f.other; + f.bind(); + const auto editor = f.other / "profiles/debug/editor"; + const auto db = editor / "generations/0123456789abcdef/compile_commands.json"; + Files::write(editor / "status.json", "{}"); + Files::write(db, "[]"); + Files::write(f.other / "compile_commands.json", "alias"); + expect(f.read(editor / "status.json", FilePurpose::status).has_value()); + expect(f.read(db, FilePurpose::native_database).has_value()); + expect(!f.read(db) && !f.read(db, FilePurpose::response)); + expect(!f.read(f.other / "compile_commands.json", FilePurpose::native_database)); + expect(!f.read(editor / "generations/not-an-id/compile_commands.json", + FilePurpose::native_database)); +} + +VOID_TEST(ProviderFiles, ordinary_workspace_link_retains_logical_and_physical_identity) { + Files f; + f.bind(); + const auto actual = f.root / "data/db", alias = f.root / "editor/compile_commands.json"; + Files::write(actual, "[]"); + fs::create_directories(alias.parent_path()); + fs::create_symlink("../data/db", alias); + auto first = f.read(alias); + require(first.has_value()); + expect(first->logical_path == alias && first->canonical_path == actual); + auto hard = f.root / "also.db"; + fs::create_hard_link(actual, hard); + auto via_alias = f.read(alias), via_hard = f.read(hard); + require(via_alias && via_hard); + expect(same_provider_object(*via_alias, *via_hard)); + fs::remove(alias); + fs::create_symlink(hard, alias); + expect(!provider_file_current(f.scope, *via_alias)); + Files::write(f.root / "replacement", "[]"); + fs::rename(f.root / "replacement", actual); + auto replacement = f.read(actual); + require(replacement.has_value()); + expect(!same_provider_object(*replacement, *via_hard)); +} + +VOID_TEST(ProviderFiles, missing_selection_is_distinct_from_dangling_link_or_reference) { + Files f; + f.bind(); + const auto selector = f.root / ".vbs/editor_selection.json"; + auto missing = f.read(selector, FilePurpose::selection); + require(!missing); + expect(missing.error().code == "missing"); + fs::create_directories(selector.parent_path()); + fs::create_symlink(f.other / "not-present", selector); + auto dangling = f.read(selector, FilePurpose::selection); + require(!dangling); + expect(dangling.error().code != "missing"); + auto status = f.read(f.root / "out/profiles/debug/editor/status.json", FilePurpose::status); + require(!status); + expect(status.error().code == "missing_reference"); +} + +VOID_TEST(ProviderFiles, bounds_and_file_kinds_are_checked_before_payload_reads) { + Files f; + f.scope.limits.max_response_file_bytes = 2; + f.bind(); + const auto path = f.root / "flags.rsp"; + Files::write(path, "abc"); + auto too_large = f.read(path, FilePurpose::response); + require(!too_large); + expect(too_large.error().code == "too_large"); + f.scope.limits.max_response_file_bytes = 1024; + expect(!f.read(path, FilePurpose::response)); + const auto fifo = f.root / "pipe"; + require(::mkfifo(fifo.c_str(), 0600) == 0); + auto nonregular = f.read(fifo); + require(!nonregular); + expect(nonregular.error().code == "not_regular"); + fs::create_symlink(f.other, f.root / "escape"); + expect(!f.read(f.root / "escape/flags.rsp", FilePurpose::response)); +} diff --git a/tests/providers/ProviderFixture.hpp b/tests/providers/ProviderFixture.hpp new file mode 100644 index 0000000..5e2569a --- /dev/null +++ b/tests/providers/ProviderFixture.hpp @@ -0,0 +1,93 @@ +#pragma once + +#include +#include +#include + +#include + +namespace provider_test { +namespace fs = std::filesystem; +namespace Build = Void::LanguageServer::Build; +namespace Protocol = Void::LanguageServer::Protocol; +using Protocol::Json; + +inline Json str(std::string_view text) { return Json{std::string{text}}; } + +inline void write_bytes(const fs::path &path, std::string_view bytes) { + fs::create_directories(path.parent_path()); + std::ofstream file(path, std::ios::binary); + file << bytes; + file.close(); + Void::Testing::require(file.good()); +} + +inline void write_json(const fs::path &path, const Json &json) { + auto bytes = Protocol::serialize_json(json); + Void::Testing::require(bytes.has_value()); + write_bytes(path, *bytes); +} + +struct Fixture { + Void::FileSystem::TempDir tmp{"vls_build_provider_"}; + fs::path root = fs::canonical(tmp.path()); + fs::path build = root / "out", selector = root / ".vbs/editor_selection.json"; + fs::path source = root / "main.cpp", compdb = root / "compile_commands.json"; + Build::ProviderScope scope{.workspace = {root, "test-editor"}}; + static constexpr std::string_view first = "0123456789abcdef", second = "fedcba9876543210"; + + Fixture() { + fs::create_directories(build); + write_bytes(source, "int main() {}\n"); + } + void bind() { + auto pinned = Build::bind_provider_scope(scope); + Void::Testing::require(pinned.has_value()); + scope = std::move(*pinned); + } + Json::Array rows() const { + Json::Array entries; + for (auto flag : {"-DVALUE=1", "-DVALUE=2"}) { + entries.push_back(Json{Json::Object{ + {"directory", str(root.string())}, + {"file", str("main.cpp")}, + {"output", str("main.o")}, + {"arguments", Json{Json::Array{str("c++"), str("-std=c++26"), str(flag), str("-c"), + str("main.cpp"), str("-o"), str("main.o")}}}}}); + } + return entries; + } + fs::path editor(std::string_view slug = "debug") const { + return build / "profiles" / slug / "editor"; + } + fs::path database(std::string_view id = first, std::string_view slug = "debug") const { + return editor(slug) / "generations" / id / "compile_commands.json"; + } + Json::Object selection(std::string_view id = first, std::string_view profile = "debug") const { + return {{"schema_version", Json{std::int64_t{1}}}, + {"ticket", Json{std::int64_t{7}}}, + {"selected_profile", str(profile)}, + {"selected_build_root", str(build.string())}, + {"selected_generation_id", str(id)}, + {"selected_compdb_path", str(database(id).string())}, + {"managed_root_alias_active", Json{false}}, + {"root_alias_warning", str("")}}; + } + Json::Object valid_status(std::string_view id = first, + std::string_view profile = "debug") const { + return {{"schema_version", Json{std::int64_t{1}}}, + {"profile", str(profile)}, + {"generation_id", str(id)}, + {"status", str("valid")}, + {"diagnostic", str("")}, + {"compdb_path", str(database(id).string())}, + {"entry_count", Json{std::int64_t{2}}}, + {"readiness_warnings", Json{Json::Array{str("generated input pending")}}}}; + } + void publish(std::string_view id = first) const { + write_json(database(id), Json{rows()}); + write_json(editor() / "status.json", Json{valid_status(id)}); + write_json(selector, Json{selection(id)}); + } +}; +} // namespace provider_test diff --git a/tests/providers/VbsProviderTests.cpp b/tests/providers/VbsProviderTests.cpp new file mode 100644 index 0000000..59e9a94 --- /dev/null +++ b/tests/providers/VbsProviderTests.cpp @@ -0,0 +1,185 @@ +#include "ProviderFixture.hpp" +#include + +namespace { +using namespace provider_test; +using namespace provider_test::Build; +using Void::Testing::expect; +using Void::Testing::require; + +VOID_TEST(VbsProvider, selects_immutable_generation_with_real_alternatives_and_warnings) { + Fixture f; + f.bind(); + f.publish(); + write_bytes(f.compdb, "unrelated root alias"); + write_bytes(f.build / "compile_commands.json", "wrong build alias"); + auto result = observe_vbs(f.scope, f.selector); + require(result.health == ProviderHealth::ready && result.generation); + expect(result.profile == "debug" && result.native_generation == Fixture::first); + expect(result.selection_ticket == 7 && result.generation->identity().provider == "vbs"); + expect(result.generation->candidates(f.source).size() == 2); + expect(result.warnings.size() == 1 && result.warnings[0].code == "readiness_warning"); + expect(!result.generation->retains_artifacts()); + for (const auto &context : result.generation->contexts()) { + expect(!context.key.target && context.key.role == ContextRole::unknown); + expect(context.original && context.original->metadata_file == f.database()); + } +} + +VOID_TEST(VbsProvider, accepts_changed_generation_at_same_ticket_and_retains_old_observation) { + Fixture f; + f.bind(); + f.publish(); + auto old = observe_vbs(f.scope, f.selector); + require(old.generation != nullptr); + f.publish(Fixture::second); + auto current = observe_vbs(f.scope, f.selector); + require(current.generation != nullptr); + expect(current.selection_ticket == old.selection_ticket); + expect(current.generation->identity().revision != old.generation->identity().revision); + expect(!provider_file_current(f.scope, old.inputs[0])); + expect(old.generation->contexts().size() == 2 && fs::exists(f.database())); +} + +VOID_TEST(VbsProvider, reserved_ticket_can_be_pending_or_retain_its_previous_tuple) { + Fixture f; + f.bind(); + auto record = f.selection(); + record["selected_generation_id"] = str(""); + record["selected_compdb_path"] = str(""); + write_json(f.selector, Json{record}); + auto pending = observe_vbs(f.scope, f.selector); + require(!pending.issues.empty()); + expect(!pending.generation && pending.issues.front().code == "selection_pending"); + f.publish(); + record = f.selection(); + record["ticket"] = Json{std::int64_t{8}}; + write_json(f.selector, Json{record}); + auto selected = observe_vbs(f.scope, f.selector); + expect(selected.selection_ticket == 8 && selected.generation != nullptr); +} + +VOID_TEST(VbsProvider, stale_and_invalid_status_cannot_reactivate_a_readable_database) { + Fixture f; + f.bind(); + f.publish(); + auto status = f.valid_status(); + status.erase("readiness_warnings"); + status.erase("entry_count"); + status["diagnostic"] = str("build is incomplete"); + for (auto state : {"stale", "invalid"}) { + status["status"] = str(state); + write_json(f.editor() / "status.json", Json{status}); + auto result = observe_vbs(f.scope, f.selector); + expect(!result.generation && result.inputs.size() == 2); + require(!result.issues.empty()); + expect(result.issues[0].message == "build is incomplete"); + } +} + +VOID_TEST(VbsProvider, directory_spellings_apply_only_to_the_build_root) { + Fixture f; + f.bind(); + f.publish(); + auto selector = f.selection(); + selector["selected_build_root"] = str(f.build.string() + "/."); + write_json(f.selector, Json{selector}); + require(observe_vbs(f.scope, f.selector).generation != nullptr); + for (const auto ending : {"/", "/.", "/.."}) { + auto bad = selector; + bad["selected_compdb_path"] = str(f.database().string() + ending); + write_json(f.selector, Json{bad}); + expect(!observe_vbs(f.scope, f.selector).generation); + write_json(f.selector, Json{selector}); + auto status = f.valid_status(); + status["compdb_path"] = str(f.database().string() + ending); + write_json(f.editor() / "status.json", Json{status}); + expect(!observe_vbs(f.scope, f.selector).generation); + write_json(f.editor() / "status.json", Json{f.valid_status()}); + } +} + +VOID_TEST(VbsProvider, rejects_disagreeing_profile_generation_count_and_alias_paths) { + Fixture f; + f.bind(); + f.publish(); + for (auto key : {"profile", "generation_id", "entry_count", "compdb_path", "schema_version"}) { + auto status = f.valid_status(); + const std::string_view field = key; + if (field == "profile") + status[key] = str("release"); + else if (field == "generation_id") + status[key] = str(Fixture::second); + else if (field == "compdb_path") + status[key] = str(f.compdb.string()); + else + status[key] = Json{std::int64_t{9}}; + write_json(f.editor() / "status.json", Json{status}); + expect(!observe_vbs(f.scope, f.selector).generation); + } +} + +VOID_TEST(VbsProvider, distinguishes_missing_selector_from_missing_selected_generation) { + Fixture f; + f.bind(); + expect(observe_vbs(f.scope, f.selector).health == ProviderHealth::missing); + f.publish(); + fs::remove(f.database()); + auto missing_db = observe_vbs(f.scope, f.selector); + expect(missing_db.health != ProviderHealth::missing && !missing_db.generation); + fs::remove(f.editor() / "status.json"); + expect(observe_vbs(f.scope, f.selector).health != ProviderHealth::missing); + write_bytes(f.selector, "{"); + expect(observe_vbs(f.scope, f.selector).health == ProviderHealth::invalid); +} + +VOID_TEST(VbsProvider, relative_locators_require_a_producer_base_or_explicit_build_root) { + Fixture f; + f.publish(); + auto selection = f.selection(), status = f.valid_status(); + auto relative_db = f.database().lexically_relative(f.root).string(); + selection["selected_build_root"] = str("out"); + selection["selected_compdb_path"] = str(relative_db); + status["compdb_path"] = str(relative_db); + write_json(f.selector, Json{selection}); + write_json(f.editor() / "status.json", Json{status}); + auto requested = f.scope; + f.bind(); + auto ambiguous = observe_vbs(f.scope, f.selector); + require(!ambiguous.issues.empty()); + expect(ambiguous.issues[0].code == "ambiguous_locator"); + requested.producer_cwd = f.root; + auto known = bind_provider_scope(requested); + require(known.has_value()); + expect(observe_vbs(*known, f.selector).generation != nullptr); + requested.producer_cwd.reset(); + requested.build_root = f.build; + auto explicit_root = bind_provider_scope(requested); + require(explicit_root.has_value()); + expect(observe_vbs(*explicit_root, f.selector).generation != nullptr); + selection["selected_compdb_path"] = str("elsewhere/" + relative_db); + write_json(f.selector, Json{selection}); + expect(!observe_vbs(*explicit_root, f.selector).generation); +} + +VOID_TEST(VbsProvider, refuses_dot_profiles_and_sanitized_component_collisions) { + Fixture f; + f.bind(); + f.publish(); + for (auto profile : {".", ".."}) { + write_json(f.selector, Json{f.selection(Fixture::first, profile)}); + expect(!observe_vbs(f.scope, f.selector).generation); + } + const auto db = f.database(Fixture::first, "a_b"); + auto select = f.selection(Fixture::first, "a/b"), + status = f.valid_status(Fixture::first, "a?b"); + select["selected_compdb_path"] = str(db.string()); + status["compdb_path"] = str(db.string()); + write_json(f.selector, Json{select}); + write_json(f.editor("a_b") / "status.json", Json{status}); + write_json(db, Json{f.rows()}); + auto mismatch = observe_vbs(f.scope, f.selector); + require(!mismatch.issues.empty()); + expect(!mismatch.generation && mismatch.issues[0].code == "invalid_status"); +} +} // namespace diff --git a/tests/reflection/ProvenanceTests.cpp b/tests/reflection/ProvenanceTests.cpp new file mode 100644 index 0000000..9b2e554 --- /dev/null +++ b/tests/reflection/ProvenanceTests.cpp @@ -0,0 +1,496 @@ +#include + +#include + +#include +#include + +#include +#include +#include + +namespace { +namespace P = Void::LanguageServer::Protocol; +using namespace vls::reflection; +using Void::Testing::expect; +using Void::Testing::require; + +Range range(std::string path, std::uint32_t line = 1) { + return {std::move(path), line, 0, line, 4}; +} + +Value integral(std::int64_t value, std::string type = "int") { + return Value{.kind = ValueKind::integral, .integral = value, .type = std::move(type)}; +} + +Value reference(std::string entity, std::string type = "State") { + return Value{.kind = ValueKind::entity, .type = std::move(type), .entity = std::move(entity)}; +} + +Member member(std::string name, Value value) { return {std::move(name), std::move(value)}; } + +Entity entity(std::string id, std::vector members = {}) { + return Entity{ + .id = std::move(id), .name = "entity", .type = "int", .members = std::move(members)}; +} + +Provenance chain(std::vector origins, bool gap = false, std::string context = "debug:a") { + return Provenance{.origins = std::move(origins), .gap = gap, .context = std::move(context)}; +} + +const Expansion::Entry *entry(const Expansion &expansion, std::string_view path) { + const auto found = std::ranges::find_if( + expansion.entries, [&](const Expansion::Entry &item) { return item.path == path; }); + return found == expansion.entries.end() ? nullptr : &*found; +} +} // namespace + +VOID_TEST(Reflection, spelling_chain_is_editable) { + const auto provenance = + chain({Origin{.kind = OriginKind::spelling, .range = range("/project/a.cpp")}}); + expect(provenance.navigable()); + expect(provenance.editable()); +} + +VOID_TEST(Reflection, generated_chain_is_navigable_but_not_editable) { + const auto synthesized = chain( + {Origin{.kind = OriginKind::splice, .range = range("/project/a.cpp")}, + Origin{.kind = OriginKind::synthesized}, + Origin{.kind = OriginKind::reflected_declaration, .range = range("/project/a.cpp", 9)}}); + expect(synthesized.navigable()); + expect(!synthesized.editable()); + const auto gapped = + chain({Origin{.kind = OriginKind::spelling, .range = range("/project/a.cpp")}}, true); + expect(gapped.navigable() && !gapped.editable()); + expect(!Provenance{}.editable()); + expect(!Provenance{}.navigable()); +} + +VOID_TEST(Reflection, expansion_projects_scalars_with_types) { + Snapshot snapshot; + require(snapshot.add( + entity("root", + {member("x", integral(17)), + member("flag", Value{.kind = ValueKind::boolean, .boolean = true, .type = "bool"}), + member("label", Value{.kind = ValueKind::text, .text = "hi", .type = "string"})}))); + const auto expansion = snapshot.expand("root"); + require(expansion.has_value()); + expect(expansion->entries.size() == 3); + const auto *x = entry(*expansion, "x"); + require(x != nullptr); + expect(x->kind == ValueKind::integral && x->text == "17" && x->type == "int" && x->depth == 1); + const auto *flag = entry(*expansion, "flag"); + require(flag != nullptr); + expect(flag->text == "true"); + const auto *label = entry(*expansion, "label"); + require(label != nullptr); + expect(label->text == "hi" && label->type == "string"); + expect(expansion->complete()); +} + +VOID_TEST(Reflection, expansion_follows_entity_members) { + Snapshot snapshot; + require(snapshot.add(entity("inner", {member("value", integral(34))}))); + require(snapshot.add(entity("outer", {member("child", reference("inner"))}))); + const auto expansion = snapshot.expand("outer"); + require(expansion.has_value()); + const auto *child = entry(*expansion, "child"); + require(child != nullptr); + expect(child->kind == ValueKind::entity && child->entity == "inner" && child->depth == 1); + const auto *value = entry(*expansion, "child.value"); + require(value != nullptr); + expect(value->text == "34" && value->depth == 2); +} + +VOID_TEST(Reflection, expansion_marks_cycles) { + Snapshot snapshot; + require( + snapshot.add(entity("a", {member("self", reference("a")), member("b", reference("b"))}))); + require( + snapshot.add(entity("b", {member("back", reference("a")), member("value", integral(1))}))); + const auto expansion = snapshot.expand("a"); + require(expansion.has_value()); + expect(std::ranges::find(expansion->cycles, std::string{"self"}) != expansion->cycles.end()); + expect(std::ranges::find(expansion->cycles, std::string{"b.back"}) != expansion->cycles.end()); + expect(!expansion->complete()); + require(entry(*expansion, "b.value") != nullptr); +} + +VOID_TEST(Reflection, expansion_bounds_depth) { + Snapshot snapshot{Limits{.expansionDepth = 1}}; + require(snapshot.add(entity("a", {member("next", reference("b"))}))); + require(snapshot.add(entity("b", {member("value", integral(2))}))); + const auto shallow = snapshot.expand("a"); + require(shallow.has_value()); + require(entry(*shallow, "next") != nullptr); + expect(entry(*shallow, "next.value") == nullptr); + expect(std::ranges::find(shallow->truncated, std::string{"next"}) != shallow->truncated.end()); + const auto deep = snapshot.expand("a", 2); + require(deep.has_value()); + require(entry(*deep, "next.value") != nullptr); + expect(deep->truncated.empty()); +} + +VOID_TEST(Reflection, expansion_bounds_total_values) { + Snapshot snapshot{Limits{.expansionValues = 2}}; + require(snapshot.add(entity( + "root", {member("a", integral(1)), member("b", integral(2)), member("c", integral(3))}))); + const auto expansion = snapshot.expand("root"); + require(expansion.has_value()); + expect(expansion->entries.size() == 2); + expect(std::ranges::find(expansion->truncated, std::string{"c"}) != expansion->truncated.end()); +} + +VOID_TEST(Reflection, expansion_preserves_opaque_and_unavailable_values) { + Snapshot snapshot; + require(snapshot.add( + entity("root", {member("opaque", Value{.kind = ValueKind::opaque, + .text = "the compiler cannot render this value", + .type = "widget"}), + member("missing", Value{.kind = ValueKind::unavailable, + .text = "not evaluated in this context"})}))); + const auto expansion = snapshot.expand("root"); + require(expansion.has_value()); + const auto *opaque = entry(*expansion, "opaque"); + require(opaque != nullptr); + expect(opaque->kind == ValueKind::opaque && + opaque->text == "the compiler cannot render this value"); + const auto *missing = entry(*expansion, "missing"); + require(missing != nullptr); + expect(missing->kind == ValueKind::unavailable && + missing->text == "not evaluated in this context"); +} + +VOID_TEST(Reflection, expansion_reports_dangling_and_unknown_entities) { + Snapshot snapshot; + require(snapshot.add(entity("root", {member("dangling", reference("absent"))}))); + const auto expansion = snapshot.expand("root"); + require(expansion.has_value()); + const auto *dangling = entry(*expansion, "dangling"); + require(dangling != nullptr); + expect(dangling->kind == ValueKind::unavailable); + expect(dangling->text == "entity is not in this snapshot"); + expect(!snapshot.expand("absent").has_value()); +} + +VOID_TEST(Reflection, snapshot_rejects_duplicate_and_oversized_entities) { + Snapshot snapshot{Limits{.entities = 2, .membersPerEntity = 1}}; + expect(snapshot.add(entity("a"))); + expect(!snapshot.add(entity("a"))); + expect(!snapshot.add(entity("b", {member("x", integral(1)), member("y", integral(2))}))); + expect(!snapshot.add(Entity{})); + expect(snapshot.add(entity("c"))); + expect(!snapshot.add(entity("d"))); +} + +VOID_TEST(Reflection, serialization_round_trip) { + Snapshot snapshot; + Entity node{.id = "node", .name = "member", .type = "int"}; + node.members = {member("next", reference("other")), member("value", integral(41))}; + node.provenance = + chain({Origin{.kind = OriginKind::spelling, .range = range("/project/a.cpp", 3)}, + Origin{.kind = OriginKind::reflected_declaration, + .range = range("/project/a.cpp", 9), + .entity = "other", + .note = "P2996"}}, + false, "debug:unit"); + node.synthesized = true; + require(snapshot.add(std::move(node))); + require(snapshot.add(entity("other", {member("value", integral(82))}))); + const auto encoded = snapshot.serialize(); + require(encoded.has_value()); + const auto parsed = Snapshot::parse(*encoded); + require(parsed.has_value()); + require(parsed->size() == snapshot.size()); + const auto *original = snapshot.find("node"); + const auto *restored = parsed->find("node"); + require(original != nullptr && restored != nullptr); + expect(*original == *restored); + const auto before = snapshot.expand("node"); + const auto after = parsed->expand("node"); + require(before.has_value() && after.has_value()); + expect(before->entries == after->entries); + expect(after->cycles.empty()); +} + +VOID_TEST(Reflection, serialization_is_canonical_across_insertion_order) { + Entity a = entity("a", {member("x", integral(1))}); + Entity b = entity("b", {member("y", integral(2))}); + Snapshot first; + require(first.add(a)); + require(first.add(b)); + Snapshot second; + require(second.add(b)); + require(second.add(a)); + const auto left = first.serialize(); + const auto right = second.serialize(); + require(left.has_value() && right.has_value()); + expect(*left == *right); +} + +VOID_TEST(Reflection, parse_rejects_unknown_schema_and_corruption) { + Snapshot snapshot; + require(snapshot.add(entity("a"))); + auto encoded = snapshot.serialize(); + require(encoded.has_value()); + auto future = *encoded; + const auto marker = future.find("\"schema\":1"); + require(marker != std::string::npos); + future.replace(marker, 10, "\"schema\":2"); + expect(!Snapshot::parse(future).has_value()); + expect(!Snapshot::parse("not json").has_value()); + expect(!Snapshot::parse("{}").has_value()); +} + +VOID_TEST(Reflection, parse_rejects_oversized_and_duplicate_input) { + Snapshot snapshot; + require(snapshot.add(entity("a"))); + require(snapshot.add(entity("b"))); + const auto encoded = snapshot.serialize(); + require(encoded.has_value()); + expect(!Snapshot::parse(*encoded, Limits{.snapshotBytes = 16}).has_value()); + auto duplicate = *encoded; + const auto second = duplicate.find("\"id\":\"b\""); + require(second != std::string::npos); + duplicate.replace(second, 8, "\"id\":\"a\""); + expect(!Snapshot::parse(duplicate).has_value()); +} + +VOID_TEST(Reflection, capabilities_report_known_support) { + Capabilities capabilities; + require(capabilities.add( + Capability{.proposal = "P2996", .facility = "splices", .supported = true})); + const auto splices = capabilities.query("P2996", "splices"); + require(splices.has_value()); + expect(splices->supported); + expect(capabilities.size() == 1); + expect(!capabilities.add(Capability{ + .proposal = "P2996", .facility = "splices", .supported = false, .reason = "duplicate"})); +} + +VOID_TEST(Reflection, capabilities_unknown_is_an_explicit_error) { + Capabilities capabilities; + require(capabilities.add(Capability{.proposal = "P2996", + .facility = "annotations", + .supported = false, + .reason = "the accepted backend lacks annotations"})); + const auto known = capabilities.query("P2996", "annotations"); + require(known.has_value()); + expect(!known->supported && !known->reason.empty()); + const auto unknown = capabilities.query("P2996", "expansionStatements"); + require(!unknown.has_value()); + expect(unknown.error().find("unknown reflection capability") != std::string::npos); + expect(!capabilities.add( + Capability{.proposal = "P2996", .facility = "staticAssert", .supported = false})); +} + +VOID_TEST(Reflection, virtual_view_renders_entity_and_members) { + Snapshot snapshot; + require(snapshot.add( + entity("root", {member("x", integral(17)), member("child", reference("inner"))}))); + require(snapshot.add(entity("inner", {member("value", integral(34))}))); + const auto expansion = snapshot.expand("root"); + require(expansion.has_value()); + const auto *root = snapshot.find("root"); + require(root != nullptr); + const auto view = render(*root, *expansion); + require(!view.lines.empty()); + expect(view.lines.front().text == "entity : int"); + expect(!view.compilable()); + const auto member_line = std::ranges::find_if(view.lines, [](const VirtualLine &line) { + return line.text.find("x : int = 17") != std::string::npos; + }); + expect(member_line != view.lines.end()); + const auto entity_line = std::ranges::find_if(view.lines, [](const VirtualLine &line) { + return line.text.find("") != std::string::npos; + }); + expect(entity_line != view.lines.end()); + expect(entity_line->text.starts_with(" ")); +} + +VOID_TEST(Reflection, virtual_view_links_source_ranges) { + Snapshot snapshot; + Entity inner = entity("inner"); + inner.provenance = + chain({Origin{.kind = OriginKind::spelling, .range = range("/p/inner.cpp", 5)}}); + Entity outer = entity("outer", {member("child", reference("inner"))}); + outer.provenance = + chain({Origin{.kind = OriginKind::spelling, .range = range("/p/outer.cpp", 9)}}); + require(snapshot.add(std::move(inner))); + require(snapshot.add(std::move(outer))); + const auto expansion = snapshot.expand("outer"); + require(expansion.has_value()); + const auto *root = snapshot.find("outer"); + require(root != nullptr); + const auto view = render(*root, *expansion); + require(!view.lines.empty()); + require(view.lines.front().link.has_value()); + expect(view.lines.front().link->path == "/p/outer.cpp" && view.lines.front().link->line == 9); + const auto child = std::ranges::find_if(view.lines, [](const VirtualLine &line) { + return line.text.find("") != std::string::npos; + }); + require(child != view.lines.end()); + require(child->link.has_value()); + expect(child->link->path == "/p/inner.cpp" && child->link->line == 5); +} + +VOID_TEST(Reflection, virtual_view_marks_cycles_and_truncation_explicitly) { + Snapshot snapshot; + require(snapshot.add( + entity("a", {member("self", reference("a")), member("next", reference("b"))}))); + require(snapshot.add(entity("b", {member("value", integral(1))}))); + const auto expansion = snapshot.expand("a", 1); + require(expansion.has_value()); + const auto *root = snapshot.find("a"); + require(root != nullptr); + const auto view = render(*root, *expansion); + const auto cycle = std::ranges::find_if( + view.lines, [](const VirtualLine &line) { return line.text.starts_with("! cycle: self"); }); + expect(cycle != view.lines.end()); + const auto truncated = std::ranges::find_if(view.lines, [](const VirtualLine &line) { + return line.text.starts_with("! truncated: next"); + }); + expect(truncated != view.lines.end()); +} + +VOID_TEST(Reflection, virtual_view_preserves_reasons_and_bounds_lines) { + Snapshot snapshot{Limits{.expansionValues = 2}}; + require(snapshot.add(entity( + "root", {member("opaque", Value{.kind = ValueKind::opaque, .text = "cannot render"}), + member("missing", Value{.kind = ValueKind::unavailable, .text = "not evaluated"}), + member("extra", integral(3))}))); + const auto expansion = snapshot.expand("root"); + require(expansion.has_value()); + const auto *root = snapshot.find("root"); + require(root != nullptr); + const auto view = render(*root, *expansion, Limits{.expansionValues = 2}); + expect(view.lines.size() == 3); + expect(view.truncated); + const auto opaque = std::ranges::find_if(view.lines, [](const VirtualLine &line) { + return line.text.find("cannot render") != std::string::npos; + }); + expect(opaque != view.lines.end()); + const auto missing = std::ranges::find_if(view.lines, [](const VirtualLine &line) { + return line.text.find("not evaluated") != std::string::npos; + }); + expect(missing != view.lines.end()); +} + +VOID_TEST(Reflection, real_compiler_splice_origin_builds_a_provenance_chain) { + // Captured verbatim from `vls_gcc_probe replay` of a sealed session that + // compiled `enum class State { Ready = 17 }; ... [:e:] ...` with the + // reproduced private GCC. The compiler reports a start coordinate only. + constexpr std::string_view recorded = + R"([{"source":"input.cpp","line":4,"byteColumn":31,"targetKind":"declaration","targetName":"Ready","targetSource":"input.cpp","targetLine":1,"targetByteColumn":20}])"; + auto parsed = P::parse_json(recorded, 8); + require(parsed.has_value()); + const auto *array = P::as_array(&*parsed); + require(array != nullptr); + std::vector origins; + for (const auto &item : *array) { + const auto *fields = P::as_object(&item); + require(fields != nullptr); + const auto *source = P::as_string(P::find_member(*fields, "source")); + const auto line = P::as_uint32(P::find_member(*fields, "line")); + const auto column = P::as_uint32(P::find_member(*fields, "byteColumn")); + const auto *kind = P::as_string(P::find_member(*fields, "targetKind")); + const auto *name = P::as_string(P::find_member(*fields, "targetName")); + const auto *target_source = P::as_string(P::find_member(*fields, "targetSource")); + const auto target_line = P::as_uint32(P::find_member(*fields, "targetLine")); + const auto target_column = P::as_uint32(P::find_member(*fields, "targetByteColumn")); + require(source && line && column && kind && name && target_source && target_line && + target_column); + origins.push_back(SpliceOrigin{.source = *source, + .line = *line, + .byteColumn = *column, + .targetKind = *kind, + .targetName = *name, + .targetSource = *target_source, + .targetLine = *target_line, + .targetByteColumn = *target_column}); + } + const auto snapshot = snapshot_from_splices(origins); + const auto *entity = snapshot.find("gcc:declaration:Ready@input.cpp:1:20"); + require(entity != nullptr); + expect(entity->name == "Ready"); + expect(!entity->synthesized); + require(entity->provenance.origins.size() == 2); + expect(entity->provenance.origins[0].kind == OriginKind::splice); + require(entity->provenance.origins[0].range.has_value()); + expect(entity->provenance.origins[0].range->line == 4); + expect(entity->provenance.origins[0].range->character == 31); + expect(entity->provenance.origins[1].kind == OriginKind::reflected_declaration); + require(entity->provenance.origins[1].range.has_value()); + expect(entity->provenance.origins[1].range->line == 1); + expect(entity->provenance.origins[1].range->character == 20); + expect(entity->provenance.navigable()); + expect(!entity->provenance.editable()); + expect(!entity->provenance.gap); + const auto expansion = snapshot.expand(entity->id); + require(expansion.has_value()); + const auto view = render(*entity, *expansion); + require(!view.lines.empty()); + expect(!view.compilable()); +} + +VOID_TEST(Reflection, splice_without_a_target_location_stays_an_explicit_gap) { + const std::vector origins{ + SpliceOrigin{.source = "/p/a.cpp", .line = 2, .byteColumn = 5, .targetKind = "value"}}; + const auto snapshot = snapshot_from_splices(origins); + require(snapshot.size() == 1); + const auto *entity = snapshot.find("gcc:value:@/p/a.cpp:2:5"); + require(entity != nullptr); + expect(entity->synthesized); + require(entity->provenance.origins.size() == 1); + expect(entity->provenance.gap); + expect(entity->provenance.navigable() && !entity->provenance.editable()); +} + +VOID_TEST(Reflection, repeated_splice_targets_keep_one_stable_identity) { + const std::vector origins{SpliceOrigin{.source = "/p/a.cpp", + .line = 2, + .byteColumn = 5, + .targetKind = "declaration", + .targetName = "f", + .targetSource = "/p/a.cpp", + .targetLine = 1, + .targetByteColumn = 4}, + SpliceOrigin{.source = "/p/a.cpp", + .line = 9, + .byteColumn = 7, + .targetKind = "declaration", + .targetName = "f", + .targetSource = "/p/a.cpp", + .targetLine = 1, + .targetByteColumn = 4}}; + const auto snapshot = snapshot_from_splices(origins); + expect(snapshot.size() == 1); + const auto *entity = snapshot.find("gcc:declaration:f@/p/a.cpp:1:4"); + require(entity != nullptr); + require(entity->provenance.origins.size() == 2); + expect(entity->provenance.origins[0].range->line == 2); +} + +VOID_TEST(Reflection, hover_and_locations_expose_source_links) { + Snapshot snapshot; + Entity node = entity("node", {member("value", integral(41))}); + node.provenance = + chain({Origin{.kind = OriginKind::splice, .range = range("/p/a.cpp", 4)}, + Origin{.kind = OriginKind::reflected_declaration, .range = range("/p/a.cpp", 1)}}); + require(snapshot.add(std::move(node))); + const auto *stored = snapshot.find("node"); + require(stored != nullptr); + const auto expansion = snapshot.expand("node"); + require(expansion.has_value()); + const auto hovered = hover(*stored, *expansion); + expect(hovered.markup.find("entity : int") != std::string::npos); + expect(hovered.markup.find("value : int = 41") != std::string::npos); + expect(hovered.markup.find("/p/a.cpp:4:0") != std::string::npos); + expect(hovered.markup.find("/p/a.cpp:1:0") != std::string::npos); + require(hovered.range.has_value()); + expect(hovered.range->line == 4); + expect(locations(stored->provenance).size() == 2); + const auto bounded = locations(stored->provenance, 1); + require(bounded.size() == 1); + expect(bounded.front().line == 4); +} diff --git a/tests/scheduler/SchedulerTests.cpp b/tests/scheduler/SchedulerTests.cpp new file mode 100644 index 0000000..dcace6a --- /dev/null +++ b/tests/scheduler/SchedulerTests.cpp @@ -0,0 +1,295 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace vls::scheduler; +using namespace std::chrono_literals; +using Void::Testing::expect; +using Void::Testing::require; + +constexpr Budget small{ + .foreground = 1, .background = 1, .artifact = 1, .queued = 8, .memory_mib = 64, .watchdog = 5s}; + +struct Gate { + std::mutex mutex; + std::condition_variable changed; + bool open{}; + void wait() { + std::unique_lock lock{mutex}; + changed.wait(lock, [&] { return open; }); + } + void release() { + std::lock_guard lock{mutex}; + open = true; + changed.notify_all(); + } +}; + +struct Terminal { + mutable std::mutex mutex; + std::condition_variable changed; + std::vector results; + + void add(Result result) { + std::lock_guard lock{mutex}; + results.push_back(std::move(result)); + changed.notify_all(); + } + std::optional wait(std::string_view key, std::uint64_t revision, + std::chrono::milliseconds timeout = 5000ms) { + std::unique_lock lock{mutex}; + changed.wait_for(lock, timeout, [&] { + for (const auto &result : results) + if (result.key == key && result.revision == revision) + return true; + return false; + }); + for (const auto &result : results) + if (result.key == key && result.revision == revision) + return result; + return std::nullopt; + } + std::size_t size() const { + std::lock_guard lock{mutex}; + return results.size(); + } +}; + +// Cooperative work that returns only when the token is stopped. +Work stopped_work(std::atomic &started, std::string detail = "stopped") { + return [&started, detail](std::stop_token token) { + started = true; + std::mutex mutex; + std::condition_variable changed; + bool stopped{}; + std::stop_callback callback{token, [&] { + std::lock_guard lock{mutex}; + stopped = true; + changed.notify_all(); + }}; + std::unique_lock lock{mutex}; + changed.wait(lock, [&] { return stopped; }); + return detail; + }; +} + +template +bool eventually(Predicate predicate, std::chrono::milliseconds timeout = 5000ms) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (std::chrono::steady_clock::now() < deadline) { + if (predicate()) + return true; + std::this_thread::sleep_for(1ms); + } + return predicate(); +} +} // namespace + +VOID_TEST(Scheduler, runs_work_and_reports_metrics) { + Scheduler scheduler{small}; + Terminal terminal; + std::atomic ran{}; + require(scheduler.submit( + {Priority::foreground, "a", 1, 1}, + [&](std::stop_token) { + ++ran; + return std::string{"ok"}; + }, + [&](Result result) { terminal.add(std::move(result)); })); + scheduler.drain(); + const auto result = terminal.wait("a", 1); + require(result.has_value()); + expect(result->outcome == Outcome::completed && result->detail == "ok"); + const auto metrics = scheduler.metrics(); + expect(metrics.accepted == 1 && metrics.completed == 1 && metrics.rejected == 0); + expect(ran == 1); +} + +VOID_TEST(Scheduler, foreground_is_reserved_while_background_is_saturated) { + Scheduler scheduler{small}; + Gate gate; + Terminal terminal; + std::atomic background_started{}; + require(scheduler.submit( + {Priority::background, "background", 1, 0}, + [&](std::stop_token) { + background_started = true; + gate.wait(); + return std::string{"background"}; + }, + [&](Result result) { terminal.add(std::move(result)); })); + require(eventually([&] { return background_started.load(); })); + require(scheduler.submit( + {Priority::foreground, "foreground", 1, 0}, + [](std::stop_token) { return std::string{"foreground"}; }, + [&](Result result) { terminal.add(std::move(result)); })); + const auto foreground = terminal.wait("foreground", 1); + require(foreground.has_value()); + expect(foreground->outcome == Outcome::completed); + expect(!terminal.wait("background", 1, 10ms).has_value()); + gate.release(); + scheduler.drain(); + require(terminal.wait("background", 1).has_value()); +} + +VOID_TEST(Scheduler, coalesces_superseded_revisions) { + Scheduler scheduler{small}; + Gate gate; + Terminal terminal; + std::atomic blocker_started{}; + require(scheduler.submit( + {Priority::foreground, "blocker", 1, 0}, + [&](std::stop_token) { + blocker_started = true; + gate.wait(); + return std::string{}; + }, + [&](Result result) { terminal.add(std::move(result)); })); + require(eventually([&] { return blocker_started.load(); })); + require(scheduler.submit( + {Priority::foreground, "document", 1, 0}, + [](std::stop_token) { return std::string{"old"}; }, + [&](Result result) { terminal.add(std::move(result)); })); + require(scheduler.submit( + {Priority::foreground, "document", 2, 0}, + [](std::stop_token) { return std::string{"new"}; }, + [&](Result result) { terminal.add(std::move(result)); })); + const auto superseded = terminal.wait("document", 1); + require(superseded.has_value()); + expect(superseded->outcome == Outcome::cancelled && superseded->detail == "superseded"); + gate.release(); + scheduler.drain(); + const auto current = terminal.wait("document", 2); + require(current.has_value()); + expect(current->outcome == Outcome::completed && current->detail == "new"); +} + +VOID_TEST(Scheduler, running_cancellation_is_cooperative) { + Scheduler scheduler{small}; + Terminal terminal; + std::atomic started{}; + require(scheduler.submit({Priority::foreground, "running", 1, 0}, stopped_work(started), + [&](Result result) { terminal.add(std::move(result)); })); + require(eventually([&] { return started.load(); })); + scheduler.cancel("running"); + const auto result = terminal.wait("running", 1); + require(result.has_value()); + expect(result->outcome == Outcome::cancelled); +} + +VOID_TEST(Scheduler, watchdog_times_out_a_stalled_task) { + Budget budget = small; + budget.watchdog = 50ms; + Scheduler scheduler{budget}; + Terminal terminal; + std::atomic started{}; + require(scheduler.submit({Priority::foreground, "stalled", 1, 0}, stopped_work(started), + [&](Result result) { terminal.add(std::move(result)); })); + require(eventually([&] { return started.load(); })); + const auto result = terminal.wait("stalled", 1); + require(result.has_value()); + expect(result->outcome == Outcome::timed_out); +} + +VOID_TEST(Scheduler, refuses_overflow_and_oversized_estimates) { + Budget budget = small; + budget.queued = 1; + budget.memory_mib = 4; + Scheduler scheduler{budget}; + Gate gate; + Terminal terminal; + std::atomic blocker_started{}; + require(scheduler.submit( + {Priority::foreground, "blocker", 1, 0}, + [&](std::stop_token) { + blocker_started = true; + gate.wait(); + return std::string{}; + }, + [&](Result result) { terminal.add(std::move(result)); })); + require(eventually([&] { return blocker_started.load(); })); + require(scheduler.submit( + {Priority::foreground, "queued", 1, 0}, [](std::stop_token) { return std::string{}; }, + [&](Result result) { terminal.add(std::move(result)); })); + expect(!scheduler.submit( + {Priority::foreground, "overflow", 1, 0}, [](std::stop_token) { return std::string{}; }, + [&](Result) {})); + expect(!scheduler.submit( + {Priority::foreground, "huge", 1, 8}, [](std::stop_token) { return std::string{}; }, + [&](Result) {})); + expect(scheduler.metrics().rejected == 1); + gate.release(); + scheduler.drain(); +} + +VOID_TEST(Scheduler, memory_budget_serializes_heavy_tasks) { + Budget budget = small; + budget.foreground = 2; + budget.memory_mib = 4; + Scheduler scheduler{budget}; + Gate gate; + Terminal terminal; + std::atomic first_started{}, second_started{}; + require(scheduler.submit( + {Priority::foreground, "first", 1, 4}, + [&](std::stop_token) { + first_started = true; + gate.wait(); + return std::string{}; + }, + [&](Result result) { terminal.add(std::move(result)); })); + require(eventually([&] { return first_started.load(); })); + require(scheduler.submit( + {Priority::foreground, "second", 1, 4}, + [&](std::stop_token) { + second_started = true; + return std::string{}; + }, + [&](Result result) { terminal.add(std::move(result)); })); + std::this_thread::sleep_for(20ms); + expect(!second_started.load()); + gate.release(); + scheduler.drain(); + expect(second_started.load()); +} + +VOID_TEST(Scheduler, every_accepted_submission_has_one_terminal_result) { + Scheduler scheduler{small}; + Terminal terminal; + std::size_t accepted{}; + for (std::uint64_t revision = 1; revision <= 100; ++revision) + accepted += + scheduler.submit( + {Priority::foreground, "document", revision, 0}, + [](std::stop_token token) { + std::this_thread::sleep_for(1ms); + return token.stop_requested() ? std::string{"stopped"} : std::string{"done"}; + }, + [&](Result result) { terminal.add(std::move(result)); }) + ? 1 + : 0; + scheduler.drain(); + expect(terminal.size() == accepted); +} + +VOID_TEST(Scheduler, rejects_invalid_budgets) { + bool threw{}; + try { + Scheduler scheduler{Budget{.foreground = 0}}; + } catch (const std::invalid_argument &) { + threw = true; + } + expect(threw); +} diff --git a/tests/semantic/DiagnosticTests.cpp b/tests/semantic/DiagnosticTests.cpp new file mode 100644 index 0000000..867aa69 --- /dev/null +++ b/tests/semantic/DiagnosticTests.cpp @@ -0,0 +1,335 @@ +#include + +#include +#include +#include + +namespace { +using namespace vls::semantic; +namespace D = Void::LanguageServer::Documents; +namespace P = Void::LanguageServer::Protocol; +using Void::Testing::expect; +using Void::Testing::require; +using namespace std::string_view_literals; + +DiagnosticSnapshot snapshot(std::string uri, std::string text, + D::PositionEncoding encoding = D::PositionEncoding::utf16) { + auto doc = std::make_shared(); + doc->identity.canonical_uri = doc->identity.display_uri = std::move(uri); + doc->text = std::move(text); + doc->line_index = D::LineIndex(doc->text); + doc->encoding = encoding; + doc->version = 7; + return doc; +} + +std::string quote(std::string_view s) { + auto out = P::serialize_json(P::Json{std::string{s}}); + require(out.has_value()); + return *out; +} + +constexpr auto primary = R"({"uri":"main.cpp","uriBaseId":"PWD"})"sv; +constexpr auto header = R"({"uri":"a.hpp","uriBaseId":"PWD"})"sv; +constexpr auto first_error = R"({"startLine":1,"startColumn":5,"endColumn":12})"sv; + +std::string artifact(std::string_view name, bool owner, + std::optional bytes = {}) { + std::string record = R"({"location":)" + std::string{name}; + if (owner) + record += R"(,"roles":["analysisTarget"])"; + if (bytes) + record += R"(,"contents":{"text":)" + quote(*bytes) + "}"; + return record + "}"; +} +std::string location(std::string_view name = primary, std::string_view region = first_error) { + return R"({"physicalLocation":{"artifactLocation":)" + std::string{name} + R"(,"region":)" + + std::string{region} + "}}"; +} +std::string issue(std::string where = location(), std::string_view level = "error", + std::string_view rule = "error", std::string_view related = {}) { + return R"({"level":)" + quote(level) + R"(,"ruleId":)" + quote(rule) + + R"(,"message":{"text":"the compiler message"},"locations":[)" + where + + R"(],"relatedLocations":[)" + std::string{related} + "]}"; +} +std::string report(bool success, std::string findings = {}, + std::string files = artifact(primary, true), + std::string_view notifications = {}) { + return R"({"version":"2.1.0","runs":[{"tool":{"driver":{"name":"GNU C++26","version":"16.2.0"}},)" + R"("originalUriBaseIds":{"PWD":{"uri":"file:///work/"}},"artifacts":[)" + + files + R"(],"invocations":[{"executionSuccessful":)" + (success ? "true" : "false") + + R"(,"toolExecutionNotifications":[)" + std::string{notifications} + + R"(]}],"results":[)" + findings + "]}]}"; +} + +struct Capture { + DiagnosticSnapshot owner; + DiagnosticJob job; + + explicit Capture(std::string bytes = "int missing;\n", + D::PositionEncoding encoding = D::PositionEncoding::utf16) + : owner(snapshot("file:///work/main.cpp", std::move(bytes), encoding)), + job{"run-17", "view-3", + owner, {{{"main.cpp", "file:///work/"}, owner}}, + true, [](const LocationRequest &) { return CoordinatePolicy{}; }} {} + + auto decode(const std::string &bytes, int status = 1) const { + return decode_gcc_diagnostics(job, + {job.invocation_id, job.input_view_id, status, true, bytes}); + } + DiagnosticBatch batch(const std::string &bytes, int status = 1) const { + auto result = decode(bytes, status); + require(result.has_value()); + return std::move(*result); + } +}; + +DiagnosticLocation primary_location(const Capture &capture, std::string_view region = first_error) { + auto batch = capture.batch(report(false, issue(location(primary, region)))); + require(batch.diagnostics.size() == 1); + return batch.diagnostics[0].location; +} +} // namespace + +VOID_TEST(DiagnosticTests, only_the_matched_owner_and_capture_can_clear) { + Capture f; + const auto wire = report(true); + const auto clean = f.batch(wire, 0); + expect(clean.complete_for_owner && clean.diagnostics.empty() && clean.owner == f.owner); + expect(clean.invocation_id == "run-17" && clean.input_view_id == "view-3"); + expect(!decode_gcc_diagnostics(f.job, {"run-18", "view-3", 0, true, wire})); + expect(!decode_gcc_diagnostics(f.job, {"run-17", "view-4", 0, true, wire})); + const auto other = snapshot("file:///work/other.cpp", f.owner->text); + f.job.artifacts.push_back({{"other.cpp", "file:///work/"}, other}); + const auto incorrect = artifact(R"({"uri":"other.cpp","uriBaseId":"PWD"})", true); + expect(!f.decode(report(true, {}, incorrect), 0)); + expect(!f.decode(report(true, {}, artifact(primary, true) + "," + incorrect), 0)); + expect(!f.decode(report(true, {}, artifact(primary, false)), 0)); + expect(!f.decode(report(true, {}, artifact(primary, true, "other content")), 0)); + f.job.inputs_complete = false; + expect(!f.batch(wire, 0).complete_for_owner); +} + +VOID_TEST(DiagnosticTests, artifact_self_indices_must_match_the_table) { + Capture f; + auto indexed = [](std::string_view name, std::string_view index, bool owner) { + return artifact(R"({"uri":")" + std::string{name} + R"(","uriBaseId":"PWD","index":)" + + std::string{index} + "}", + owner); + }; + const auto clean = f.batch( + report(true, {}, indexed("a.hpp", "0", false) + "," + indexed("main.cpp", "1", true)), 0); + expect(clean.complete_for_owner && clean.diagnostics.empty()); + const auto second = indexed("a.hpp", "1", false); + for (std::string_view index : {"999", R"("0")", "1", "0.0", "-1", "null"}) { + const auto rejected = + f.decode(report(true, {}, indexed("main.cpp", index, true) + "," + second), 0); + expect(!rejected && rejected.error() == DiagnosticError::malformed_report); + } + const auto rejected = f.decode( + report(true, {}, indexed("main.cpp", "0", true) + "," + indexed("a.hpp", "0", false)), 0); + expect(!rejected && rejected.error() == DiagnosticError::malformed_report); +} + +VOID_TEST(DiagnosticTests, source_error_and_warning_keep_message_rule_and_related_evidence) { + Capture f; + const auto note = snapshot("file:///work/a.hpp", "int missing;\n"); + f.job.artifacts.push_back({{"a.hpp", "file:///work/"}, note}); + const auto files = + artifact(primary, true, f.owner->text) + "," + artifact(header, false, note->text); + auto related = location(R"({"index":1})") + "," + location(header, R"({"startLine":1})"); + const auto batch = f.batch(report(false, issue(location(), "error", "error", related), files)); + require(batch.diagnostics.size() == 1); + const auto &d = batch.diagnostics.front(); + expect(batch.complete_for_owner && d.severity == DiagnosticSeverity::error && + d.rule == "error" && d.message == "the compiler message"); + expect(d.location.snapshot == f.owner && d.location.range == D::Range{{0, 4}, {0, 11}}); + require(d.related.size() == 2); + expect(d.related[0].location.snapshot == note && + d.related[0].location.range == d.location.range); + expect(d.related[1].message.empty() && + d.related[1].location.gap == LocationGap::incomplete_region); + const auto warning = + f.batch(report(true, issue(location(), "warning", "-Wdeprecated-declarations")), 0); + expect(warning.complete_for_owner && + warning.diagnostics[0].severity == DiagnosticSeverity::warning); +} + +VOID_TEST(DiagnosticTests, source_text_alone_cannot_map_a_remapped_occurrence) { + Capture f{"#if 0\nint missing;\n#endif\n#include \"alias.hpp\"\n"}; + const auto alias = snapshot("file:///work/alias.hpp", "#line 2 \"main.cpp\"\nint missing;\n"); + f.job.artifacts.push_back({{"alias.hpp", "file:///work/"}, alias}); + f.job.physical_origin = {}; + const auto d = f.batch( + report(false, issue(location(primary, R"({"startLine":2,"startColumn":5,"endColumn":12})")), + artifact(primary, true, f.owner->text))); + expect(!d.complete_for_owner && d.diagnostics[0].message == "the compiler message" && + d.diagnostics[0].location.gap == LocationGap::unproven_origin); +} + +VOID_TEST(DiagnosticTests, literal_artifact_names_and_indices_bind_exactly) { + Capture f; + const auto space = snapshot("file:///work/a%20b.cpp", "int missing;\n"); + const auto percent = snapshot("file:///work/a%2520b.cpp", space->text); + f.job.artifacts.push_back({{"a b.cpp", ""}, space}); + f.job.artifacts.push_back({{"a%20b.cpp", ""}, percent}); + const auto files = artifact(primary, true) + "," + artifact(R"({"uri":"a b.cpp"})", false) + + "," + artifact(R"({"uri":"a%20b.cpp"})", false); + auto locate = [&](std::string_view name) { + return f.batch(report(false, issue(location(name)), files)).diagnostics.front().location; + }; + expect(locate(R"({"uri":"a%20b.cpp","index":2})").snapshot == percent); + expect(locate(R"({"index":1})").snapshot == space); + expect(locate(R"({"uri":"a%20b.cpp","index":1})").gap == LocationGap::unknown_artifact); + expect(locate(R"({"uri":"a b.cpp","uriBaseId":"wrong"})").gap == LocationGap::unknown_artifact); + expect(locate(R"({"index":1.00000000000000001})").gap == LocationGap::unknown_artifact); + const auto stale = + artifact(primary, true) + "," + artifact(R"({"uri":"a b.cpp"})", false, "old"); + expect(f.batch(report(false, issue(location(R"({"index":1})")), stale)) + .diagnostics[0] + .location.gap == LocationGap::artifact_mismatch); +} + +VOID_TEST(DiagnosticTests, certified_byte_positions_use_the_negotiated_encoding) { + for (auto encoding : {D::PositionEncoding::utf8, D::PositionEncoding::utf16}) { + Capture f{"\t😀é missing;\r\n", encoding}; + f.job.physical_origin = [](const LocationRequest &) { + return CoordinatePolicy{ColumnUnit::utf8_bytes}; + }; + const auto loc = primary_location(f, R"({"startLine":1,"startColumn":10,"endColumn":17})"); + const std::uint32_t start = encoding == D::PositionEncoding::utf8 ? 9 : 6; + expect(loc.range == D::Range{{0, start}, {0, start + 7}}); + expect(primary_location(f, R"({"startLine":1,"startColumn":3,"endColumn":17})").gap == + LocationGap::ambiguous_column); + f.job.physical_origin = [](const LocationRequest &) { + return CoordinatePolicy{ColumnUnit::gcc_display}; + }; + expect(primary_location(f, R"({"startLine":1,"startColumn":16,"endColumn":23})").gap == + LocationGap::ambiguous_column); + } +} + +VOID_TEST(DiagnosticTests, display_columns_withhold_ambiguous_zero_width_boundaries) { + const auto wire = report( + false, issue(location(primary, R"({"startLine":1,"startColumn":16,"endColumn":17})"))); + for (const auto unit : {ColumnUnit::ascii_consensus, ColumnUnit::gcc_display}) { + const auto policy = [unit](const LocationRequest &) { return CoordinatePolicy{unit}; }; + for (const char *source : {"int f(){return e\u0301;}\n", "int f(){return y\u200d;}\n", + "int f(){return e\u0301\u200d;}\n"}) { + Capture f{source}; + f.job.physical_origin = policy; + const auto batch = f.batch(wire); + require(batch.diagnostics.size() == 1); + const auto &diagnostic = batch.diagnostics.front(); + expect(!batch.complete_for_owner && diagnostic.message == "the compiler message"); + expect(diagnostic.location.gap == LocationGap::ambiguous_column && + !diagnostic.location.range); + } + Capture leading{"\u0301x\nz\n"}; + leading.job.physical_origin = policy; + expect(primary_location(leading, + R"({"startLine":1,"startColumn":1,"endLine":2,"endColumn":2})") + .gap == LocationGap::ambiguous_column); + + Capture ascii{"int f(){return yy;} // \u0301\n"}; + ascii.job.physical_origin = policy; + expect( + primary_location(ascii, R"({"startLine":1,"startColumn":16,"endColumn":18})").range == + D::Range{{0, 15}, {0, 17}}); + } +} + +VOID_TEST(DiagnosticTests, certified_byte_columns_distinguish_zero_width_boundaries) { + for (const auto encoding : {D::PositionEncoding::utf8, D::PositionEncoding::utf16}) { + Capture f{"e\u0301;\n", encoding}; + f.job.physical_origin = [](const LocationRequest &) { + return CoordinatePolicy{ColumnUnit::utf8_bytes}; + }; + expect(primary_location(f, R"({"startLine":1,"startColumn":1,"endColumn":2})").range == + D::Range{{0, 0}, {0, 1}}); + const std::uint32_t end = encoding == D::PositionEncoding::utf8 ? 3 : 2; + expect(primary_location(f, R"({"startLine":1,"startColumn":1,"endColumn":4})").range == + D::Range{{0, 0}, {0, end}}); + } +} + +VOID_TEST(DiagnosticTests, tabstop_and_first_line_bom_require_known_producer_units) { + Capture tab{"\tmissing;\n"}; + for (const unsigned width : {4u, 8u}) { + tab.job.physical_origin = [width](const LocationRequest &) { + return CoordinatePolicy{ColumnUnit::gcc_display, width}; + }; + const auto region = R"({"startLine":1,"startColumn":)" + std::to_string(width + 1) + + R"(,"endColumn":)" + std::to_string(width + 8) + "}"; + expect(primary_location(tab, region).range == D::Range{{0, 1}, {0, 8}}); + expect(primary_location(tab, R"({"startLine":1,"startColumn":2,"endColumn":3})").gap == + LocationGap::ambiguous_column); + } + Capture bom{"\xef\xbb\xbfmissing;\n"}; + const auto region = R"({"startLine":1,"startColumn":1,"endColumn":8})"; + expect(primary_location(bom, region).gap == LocationGap::ambiguous_column); + bom.job.physical_origin = [](const LocationRequest &) { + return CoordinatePolicy{ColumnUnit::utf8_bytes, 8, FirstLineBom::skipped}; + }; + expect(primary_location(bom, region).range == D::Range{{0, 1}, {0, 8}}); +} + +VOID_TEST(DiagnosticTests, invalid_lines_offsets_and_numeric_variants_never_clamp) { + Capture f; + for (std::string_view r : {R"({"startLine":0,"startColumn":1,"endColumn":2})", + R"({"startLine":1,"startColumn":1.00000000000000001,"endColumn":2})", + R"({"startLine":1,"startColumn":3,"endColumn":2})", + R"({"startLine":1,"startColumn":1,"endColumn":2147483648})"}) + expect(primary_location(f, r).gap == LocationGap::incomplete_region); + for (std::string_view r : {R"({"startLine":1,"startColumn":1,"endColumn":14})", + R"({"startLine":3,"startColumn":1,"endColumn":2})"}) + expect(primary_location(f, r).gap == LocationGap::ambiguous_column); +} + +VOID_TEST(DiagnosticTests, early_failures_preserve_the_problem_without_clearing_diagnostics) { + Capture f; + auto fatal = f.batch(report(false, issue(location(), "error", "fatal error"))); + expect(!fatal.complete_for_owner && fatal.diagnostics.front().location.range.has_value()); + auto before_open = f.batch(report(false, issue("", "error", "fatal error"), {})); + expect(!before_open.complete_for_owner && + before_open.diagnostics.front().message == "the compiler message"); + auto unknown = f.batch(report(false, issue(), artifact(primary, false))); + expect(!unknown.complete_for_owner && + unknown.diagnostics[0].location.gap == LocationGap::unknown_artifact); +} + +VOID_TEST(DiagnosticTests, incomplete_process_and_malformed_reports_cannot_clear) { + Capture f; + const auto wire = report(true); + for (const auto &out : {DiagnosticOutput{"run-17", "view-3", {}, true, wire}, + DiagnosticOutput{"run-17", "view-3", 126, true, wire}, + DiagnosticOutput{"run-17", "view-3", 0, false, wire}, + DiagnosticOutput{"run-17", "view-3", 1, true, {}}}) + expect(!decode_gcc_diagnostics(f.job, out)); + expect(!f.decode(wire)); + expect(!f.decode(report(false))); + expect(!f.decode(report(true, issue()), 0)); + expect(!f.decode(report(false, issue(location(), "warning")))); + expect(!f.decode(report(true, {}, artifact(primary, true), "{}"), 0)); + expect(!f.decode(wire.substr(0, wire.size() - 1), 0)); +} + +VOID_TEST(DiagnosticTests, report_structure_and_output_sizes_are_bounded) { + Capture f; + expect(f.decode(std::string(4 * 1024 * 1024 + 1, ' '), 0).error() == + DiagnosticError::resource_limit); + std::string repeated = "[0"; + for (unsigned i = 0; i < 150000; ++i) + repeated += ",0"; + expect(f.decode(repeated + "]").error() == DiagnosticError::resource_limit); + auto findings = issue(); + const auto pos = findings.find("the compiler message"); + require(pos != findings.npos); + findings.replace(pos, 20, 65537, 'x'); + expect(f.decode(report(false, findings)).error() == DiagnosticError::resource_limit); + const auto quoted_text = std::string(150000, ','); + expect(f.decode(report(true, {}, + artifact(primary, true) + "," + artifact(header, false, quoted_text)), + 0) + .has_value()); +} diff --git a/tests/semantic/GccDiagnosticFixture.cpp b/tests/semantic/GccDiagnosticFixture.cpp new file mode 100644 index 0000000..8503f31 --- /dev/null +++ b/tests/semantic/GccDiagnosticFixture.cpp @@ -0,0 +1,260 @@ +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace P = Void::LanguageServer::Protocol; +namespace D = Void::LanguageServer::Documents; +using namespace vls::semantic; + +std::string bounded_read(std::istream &stream) { + constexpr std::size_t limit = 4 * 1024 * 1024; + std::string bytes; + std::array chunk; + while (stream.read(chunk.data(), chunk.size()) || stream.gcount()) { + const auto count = static_cast(stream.gcount()); + if (count > limit - bytes.size()) + throw std::runtime_error("fixture stream too large"); + bytes.append(chunk.data(), count); + } + if (!stream.eof() || stream.bad()) + throw std::runtime_error("incomplete fixture stream"); + return bytes; +} + +unsigned number(std::string_view input) { + unsigned result{}; + const auto [end, error] = std::from_chars(input.data(), input.data() + input.size(), result); + if (error != std::errc{} || end != input.data() + input.size()) + throw std::runtime_error("invalid fixture number"); + return result; +} + +P::Json position(const D::Position &p) { + return P::Json{ + P::Json::Array{P::Json{std::int64_t{p.line}}, P::Json{std::int64_t{p.character}}}}; +} + +P::Json describe_command(std::span args) { + namespace W = Void::LanguageServer::Workspace; + const std::string_view mode{args.front()}; + const bool analyze = mode == "--analyze"; + const bool capture = mode == "--capture-disk" || mode == "--capture-overlay"; + const std::size_t required = capture ? 5 : 4; + if (args.size() != required && args.size() != required + 1) + throw std::runtime_error("expected WORKSPACE SOURCE GCC, a capture file if selected, and " + "optional COMPILE_COMMANDS"); + const std::filesystem::path root{args[1]}, source{args[2]}; + std::filesystem::path driver{args[3]}; + std::shared_ptr profile; + if (analyze) { + auto loaded = GccProfile::load(driver); + if (!loaded) + throw std::runtime_error(loaded.error()); + profile = std::move(*loaded); + driver = profile->driver; + } + if (!root.is_absolute() || !source.is_absolute() || !driver.is_absolute()) + throw std::runtime_error("expected absolute context fixture paths"); + W::SettingsOverrides overrides; + overrides.provider = + args.size() == required ? W::ProviderPreference::vbs : W::ProviderPreference::compdb; + if (args.size() > required) + overrides.compdb_path = args[required]; + overrides.tool_approvals = {{root, W::AuthorityLevel::compiler_use, driver}}; + vls::WorkspaceSession session( + {.root = root, .cli_settings = W::settings_from_cli(std::move(overrides), root)}); + const auto root_uri = D::path_to_file_uri(root); + const auto doc_uri = D::path_to_file_uri(source); + const P::Json folder{P::Json::Object{{"uri", P::Json{root_uri}}}}; + if (auto initialized = session.initialize( + P::Json{P::Json::Object{{"workspaceFolders", P::Json{P::Json::Array{folder}}}}}); + !initialized) + throw std::runtime_error(initialized.error()); + auto lease = + session.acquire_semantic_context(doc_uri, root_uri, {driver, W::CompilerDriver::gcc}); + if (!lease) + throw std::runtime_error(lease.error().message); + const auto &selection = lease->selection(); + const auto *row = selection->selected; + if (!row || !row->semantic_arguments || !row->original || !row->working_directory || + row->source_language != "c++" || row->key.owning_tu != source) + throw std::runtime_error("the selected row has no checked C++ command"); + if (analyze) { + D::DocumentStore documents; + if (!documents.open(doc_uri, "cpp", 1, bounded_read(std::cin))) + throw std::runtime_error("cannot open compiler fixture document"); + SourceCatalog catalog{documents}; + const SourceScope scope{selection->generation->identity().workspace, + lease->configuration_generation(), + lease->driver().tool.trust_generation}; + auto grant = catalog.install(scope, std::array{root}); + if (!grant) + throw std::runtime_error("could not grant selected source root"); + auto result = analyze_with_gcc(*profile, *lease, documents, catalog, *grant, 1, {}, {}); + if (!result) + throw std::runtime_error(result.error()); + P::Json::Array diagnostics; + for (auto &d : result->batch.diagnostics) { + P::Json range{nullptr}; + if (d.location.range) + range = P::Json{P::Json::Array{position(d.location.range->start), + position(d.location.range->end)}}; + diagnostics.emplace_back( + P::Json::Object{{"message", P::Json{d.message}}, {"range", std::move(range)}}); + } + return P::Json{P::Json::Object{ + {"complete", P::Json{result->batch.complete_for_owner}}, + {"compilerRuns", P::Json{static_cast(result->compiler_runs)}}, + {"lookups", P::Json{static_cast(result->lookups.size())}}, + {"unprovenOrigin", result->unproven_location_origin + ? P::Json{result->unproven_location_origin->native()} + : P::Json{nullptr}}, + {"diagnostics", P::Json{std::move(diagnostics)}}}}; + } + if (capture) { + const std::filesystem::path file{args[4]}; + const auto uri = D::path_to_file_uri(file); + D::DocumentStore documents; + if (mode == "--capture-overlay") { + if (auto opened = documents.open(uri, "cpp", 1, bounded_read(std::cin)); !opened) + throw std::runtime_error(opened.error().message); + } + SourceCatalog catalog{documents}; + const SourceScope job{selection->generation->identity().workspace, + lease->configuration_generation(), + lease->driver().tool.trust_generation}; + // The fixture explicitly grants its workspace, including its prepared library generation. + const std::array roots{root}; + auto grant = catalog.install(job, roots); + auto census = documents.file_overlay_inventory(); + if (!grant || !census) + throw std::runtime_error("could not bind source authority for the selected fixture"); + std::vector names{{source}}; + if (file != source) + names.push_back({file}); + auto captured = + catalog.capture(job, *grant, *census, names, + {.files = 2, .file_bytes = 512 * 1024, .total_bytes = 1024 * 1024}); + if (!captured) + throw std::runtime_error("fixture source was unavailable for capture"); + auto current = session.validate_semantic_context(*lease); + if (!current || !catalog.validate(job, **captured)) + throw std::runtime_error("the selected command or source changed during capture"); + const auto &doc = (*captured)->entries().back().snapshot; + return P::Json{ + P::Json::Object{{"uri", P::Json{doc->identity.canonical_uri}}, + {"text", P::Json{doc->text}}, + {"overlay", P::Json{doc->origin == D::DocumentOrigin::overlay}}}}; + } + P::Json::Array arguments; + for (const auto &arg : *row->semantic_arguments) + arguments.emplace_back(arg); + if (auto valid = session.validate_semantic_context(*lease); !valid) + throw std::runtime_error(valid.error().message); + return P::Json{ + P::Json::Object{{"directory", P::Json{row->working_directory->native()}}, + {"file", P::Json{row->key.owning_tu.native()}}, + {"database", P::Json{row->original->metadata_file.native()}}, + {"provider", P::Json{selection->generation->identity().provider}}, + {"driverSha256", P::Json{lease->driver().tool.identity.content_hash_hex}}, + {"arguments", P::Json{std::move(arguments)}}}}; +} +} // namespace + +int main(int argc, char **argv) { + try { + std::span args{argv + 1, static_cast(argc - 1)}; + const std::string_view mode = + args.empty() ? std::string_view{} : std::string_view{args.front()}; + if (mode == "--command" || mode == "--capture-disk" || mode == "--capture-overlay" || + mode == "--analyze") { + std::cout << P::serialize_json(describe_command(args)).value() << '\n'; + return 0; + } + std::filesystem::path logical_source; + if (args.size() >= 2 && std::string_view{args[0]} == "--logical-file") { + logical_source = args[1]; + if (!logical_source.is_absolute() || + logical_source != logical_source.lexically_normal()) + throw std::runtime_error("expected a normalized absolute compiler input name"); + args = args.subspan(2); + } + if (args.size() != 2 && args.size() != 5) + throw std::runtime_error( + "expected source and status, optionally a witnessed line/start/end"); + const std::filesystem::path source{args[0]}; + const unsigned status = number(args[1]); + if (source != source.filename() || source.empty() || status > 1) + throw std::runtime_error("expected a local fixture filename and compiler exit 0 or 1"); + std::ifstream input(source, std::ios::binary); + if (!input) + throw std::runtime_error("cannot open the supplied source snapshot"); + auto doc = std::make_shared(); + const auto logical = + logical_source.empty() ? std::filesystem::absolute(source) : logical_source; + const auto uri = D::path_to_file_uri(logical); + doc->identity = {uri, uri, logical, true}; + doc->text = bounded_read(input); + doc->line_index = D::LineIndex(doc->text); + doc->version = 1; + // GCC writes the producer's literal working directory in originalUriBaseIds. + auto base = "file://" + std::filesystem::current_path().native(); + if (!base.ends_with('/')) + base += '/'; + ArtifactName artifact = logical_source.empty() ? ArtifactName{source.native(), base} + : ArtifactName{logical_source.native(), {}}; + DiagnosticJob job{ + "fixture-run", "fixture-view", doc, {{std::move(artifact), doc}}, true, {}}; + if (args.size() == 5) { + // The test runner supplies the single physical occurrence witnessed by its edit. + const unsigned line = number(args[2]), first = number(args[3]), end = number(args[4]); + job.physical_origin = + [=](const LocationRequest &request) -> std::optional { + const auto &r = request.region; + if (!request.related && r.first_line == line && r.last_line == line && + r.first_column == first && r.end_column == end) + return CoordinatePolicy{}; + return std::nullopt; + }; + } + const auto report = bounded_read(std::cin); + auto batch = decode_gcc_diagnostics( + job, {job.invocation_id, job.input_view_id, static_cast(status), true, report}); + if (!batch) { + std::cerr << "diagnostic adapter rejected report (" << static_cast(batch.error()) + << ")\n"; + return 1; + } + P::Json::Array diagnostics; + for (const auto &d : batch->diagnostics) { + P::Json range{nullptr}; + if (d.location.range) + range = P::Json{P::Json::Array{position(d.location.range->start), + position(d.location.range->end)}}; + diagnostics.emplace_back(P::Json::Object{{"message", P::Json{d.message}}, + {"rule", P::Json{d.rule}}, + {"range", std::move(range)}}); + } + auto bytes = P::serialize_json( + P::Json{P::Json::Object{{"complete", P::Json{batch->complete_for_owner}}, + {"diagnostics", P::Json{std::move(diagnostics)}}}}); + if (!bytes) + throw std::runtime_error(bytes.error()); + std::cout << *bytes << '\n'; + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tests/semantic/OccurrenceTests.cpp b/tests/semantic/OccurrenceTests.cpp new file mode 100644 index 0000000..e90e747 --- /dev/null +++ b/tests/semantic/OccurrenceTests.cpp @@ -0,0 +1,188 @@ +#include + +#include +#include + +#include +#include +#include +#include + +namespace { +namespace D = Void::LanguageServer::Documents; +using namespace vls::semantic; +using Void::Testing::expect; +using Void::Testing::require; + +constexpr std::string_view nonce = "0123456789abcdef0123456789abcdef"; +constexpr std::string_view path = "/workspace/unit.cpp"; + +std::shared_ptr +snapshot(std::string text, D::PositionEncoding encoding = D::PositionEncoding::utf16) { + auto value = std::make_shared(); + value->text = std::move(text); + value->line_index = D::LineIndex(value->text); + value->encoding = encoding; + return value; +} + +std::vector capture(std::string text, + D::PositionEncoding encoding = D::PositionEncoding::utf16) { + std::vector entries; + entries.push_back({path, snapshot(std::move(text), encoding), SourceNode::regular, {}}); + return entries; +} + +struct Span { + std::uint32_t line, start, end; +}; + +Span span(std::string_view text, std::string_view name, std::size_t ordinal = 0) { + std::size_t offset = 0; + for (std::size_t found = 0; found <= ordinal; ++found) { + offset = text.find(name, offset); + require(offset != std::string_view::npos); + if (found != ordinal) + offset += name.size(); + } + std::uint32_t line = 1; + std::size_t line_start = 0; + for (std::size_t i = 0; i != offset; ++i) + if (text[i] == '\n') { + ++line; + line_start = i + 1; + } + return {line, static_cast(offset - line_start + 1), + static_cast(offset - line_start + 1 + name.size())}; +} + +std::string span_json(std::string_view where, const Span &value) { + return R"({"path":")" + std::string{where} + R"(","line":)" + std::to_string(value.line) + + R"(,"startByte":)" + std::to_string(value.start) + R"(,"endByte":)" + + std::to_string(value.end) + "}"; +} + +std::string occurrence(std::string_view name, std::string_view type, const std::string &use, + const std::string &definition) { + return R"({"name":")" + std::string{name} + R"(","type":")" + std::string{type} + + R"(","canonicalType":")" + std::string{type} + + R"sig(","signature":"int f(int)","use":)sig" + use + R"(,"definition":)" + definition + + "}"; +} + +std::string report(std::string_view occurrences, bool complete = true, bool partial = false, + std::string_view reason = "", std::string_view selected = nonce) { + return R"({"schema":1,"nonce":")" + std::string{selected} + R"(","complete":)" + + (complete ? "true" : "false") + R"(,"partial":)" + (partial ? "true" : "false") + + R"(,"reason":")" + std::string{reason} + R"(","occurrences":[)" + + std::string{occurrences} + "]}"; +} + +auto decode(std::string_view text, std::span entries) { + return decode_occurrences(text, nonce, entries); +} +} // namespace + +constexpr std::string_view source = "int f(int v) { return v; }\nint q() { return f(1); }\n"; + +VOID_TEST(Occurrences, binds_use_and_definition) { + auto entries = capture(std::string{source}); + const auto call = span(source, "f", 1), declaration = span(source, "f", 0); + auto decoded = + decode(report(occurrence("f", "int", span_json(path, call), span_json(path, declaration))), + entries); + require(decoded.has_value()); + require(decoded->complete && !decoded->partial); + require(decoded->occurrences.size() == 1); + const auto &fact = decoded->occurrences.front(); + expect(fact.name == "f" && fact.type == "int" && fact.canonical_type == "int"); + expect(fact.signature == "int f(int)"); + require(fact.has_definition()); + const auto offset = entries.front().snapshot->position_to_offset(fact.use.start); + require(offset.has_value()); + expect(entries.front().snapshot->text.substr(*offset, 1) == "f"); +} + +VOID_TEST(Occurrences, rejects_wrong_nonce) { + auto entries = capture(std::string{source}); + const auto call = span(source, "f", 1); + auto decoded = decode(report(occurrence("f", "int", span_json(path, call), "null"), true, false, + "", "ffffffffffffffffffffffffffffffff"), + entries); + require(!decoded.has_value()); + expect(decoded.error() == OccurrenceError::wrong_nonce); +} + +VOID_TEST(Occurrences, rejects_unknown_path) { + auto entries = capture(std::string{source}); + const auto call = span(source, "f", 1); + auto decoded = decode( + report(occurrence("f", "int", span_json("/workspace/other.cpp", call), "null")), entries); + require(!decoded.has_value()); + expect(decoded.error() == OccurrenceError::invalid_report); +} + +VOID_TEST(Occurrences, rejects_mismatched_bytes) { + auto entries = capture(std::string{source}); + auto call = span(source, "f", 1); + ++call.start; + auto decoded = decode(report(occurrence("f", "int", span_json(path, call), "null")), entries); + require(!decoded.has_value()); + expect(decoded.error() == OccurrenceError::invalid_report); +} + +VOID_TEST(Occurrences, incomplete_publishes_no_facts) { + auto entries = capture(std::string{source}); + const auto call = span(source, "f", 1); + auto decoded = decode( + report(occurrence("f", "int", span_json(path, call), "null"), false, false, "capacity"), + entries); + require(decoded.has_value()); + expect(!decoded->complete && decoded->reason == "capacity" && decoded->occurrences.empty()); +} + +VOID_TEST(Occurrences, converts_through_the_negotiated_encoding) { + const std::string text = "int q(){ /*\xF0\x9F\x99\x82*/ return f(1); }\n"; + for (const auto encoding : {D::PositionEncoding::utf16, D::PositionEncoding::utf8}) { + auto entries = capture(text, encoding); + const auto call = span(text, "f"); + auto decoded = + decode(report(occurrence("f", "int", span_json(path, call), "null")), entries); + require(decoded.has_value()); + const auto &fact = decoded->occurrences.front(); + const auto prefix = text.substr(0, text.find('f')); + const auto expected = encoding == D::PositionEncoding::utf16 + ? prefix.size() - 4 + 2 // emoji: 4 bytes, 2 UTF-16 units + : prefix.size(); + expect(fact.use.start.character == expected); + } +} + +VOID_TEST(Occurrences, rejects_duplicate_uses) { + auto entries = capture(std::string{source}); + const auto call = span(source, "f", 1); + const auto item = occurrence("f", "int", span_json(path, call), "null"); + auto decoded = decode(report(item + "," + item), entries); + require(!decoded.has_value()); + expect(decoded.error() == OccurrenceError::invalid_report); +} + +VOID_TEST(Occurrences, withholds_a_definition_outside_the_capture) { + auto entries = capture(std::string{source}); + const auto call = span(source, "f", 1); + auto decoded = decode(report(occurrence("f", "int", span_json(path, call), + span_json("/workspace/header.hpp", call))), + entries); + require(decoded.has_value()); + require(decoded->occurrences.size() == 1); + expect(!decoded->occurrences.front().has_definition()); +} + +VOID_TEST(Occurrences, rejects_a_malformed_envelope) { + auto entries = capture(std::string{source}); + const auto call = span(source, "f", 1); + auto extra = report(occurrence("f", "int", span_json(path, call), "null")); + extra.insert(extra.size() - 1, R"(,"extra":1)"); + require(!decode(extra, entries).has_value()); + require(!decode("{\"schema\":1}", entries).has_value()); +} diff --git a/tests/semantic/SourceCatalogTests.cpp b/tests/semantic/SourceCatalogTests.cpp new file mode 100644 index 0000000..d1d4e77 --- /dev/null +++ b/tests/semantic/SourceCatalogTests.cpp @@ -0,0 +1,362 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +namespace D = Void::LanguageServer::Documents; +using namespace vls::semantic; +using Void::Testing::expect; +using Void::Testing::require; + +struct Files { + Void::FileSystem::TempDir temp{"vls_source_catalog_"}; + fs::path root = fs::canonical(temp.path()) / "workspace"; + fs::path external = root.parent_path() / "external"; + SourceScope scope{{root, "workspace-1"}, 3, 5}; + D::DocumentStore documents; + SourceCatalog catalog; + InstalledSourceGrant grant; + + explicit Files(std::function hook = {}, D::DocumentLimits limits = {}) + : documents(D::PositionEncoding::utf16, limits), catalog(documents, std::move(hook)) { + fs::create_directories(root / "nested"); + fs::create_directory(external); + grant = install({root}); + } + InstalledSourceGrant install(std::initializer_list roots) { + auto result = catalog.install(scope, roots); + require(result.has_value()); + return *result; + } + D::FileOverlayInventory census() const { + auto result = documents.file_overlay_inventory(); + require(result.has_value()); + return std::move(*result); + } + auto take(std::initializer_list requests, SourceLimits limits = {}) { + return catalog.capture(scope, grant, census(), requests, limits); + } + static void write(const fs::path &path, std::string_view text) { + std::ofstream out(path, std::ios::binary); + out << text; + out.close(); + require(out.good()); + } + auto open(const fs::path &path, std::string text) { + return documents.open(D::path_to_file_uri(path), "cpp", 1, std::move(text)); + } +}; + +void failed(const auto &result, SourceIssue issue) { + require(!result.has_value()); + expect(result.error().issue == issue); +} + +class AccessWatch { + Void::System::OwnedFd events_{::inotify_init1(IN_NONBLOCK | IN_CLOEXEC)}; + + public: + explicit AccessWatch(const fs::path &path) { + require(events_ && ::inotify_add_watch(events_.get(), path.c_str(), IN_ACCESS) >= 0); + } + bool accessed() const { + alignas(inotify_event) std::array buffer; + auto n = ::read(events_.get(), buffer.data(), buffer.size()); + require(n > 0 || (n < 0 && errno == EAGAIN)); + return n > 0; + } +}; +} // namespace + +VOID_TEST(SourceCatalogTests, lookup_captures_directories_and_regular_presence_without_reading) { + Files f; + const auto dir = f.root / "nested", file = dir / "input.hpp"; + Files::write(file, "one"); + AccessWatch watch(file); + auto capture = f.take({{f.root, true, true}, {dir, true, true}, {file, true, true}}); + require(capture.has_value()); + const auto entries = (*capture)->entries(); + expect(entries[0].node == SourceNode::directory && entries[1].node == SourceNode::directory); + expect(entries[2].node == SourceNode::regular && !entries[2].snapshot); + expect(!watch.accessed()); + Files::write(dir / "unrelated.hpp", ""); + expect(f.catalog.validate(f.scope, **capture).has_value()); + Files::write(file, "two"); + failed(f.catalog.validate(f.scope, **capture), SourceIssue::changed); +} + +VOID_TEST(SourceCatalogTests, first_missing_directory_invalidates_deeper_optional_lookup) { + Files f; + const auto dir = f.root / "future", file = dir / "deeper" / "optional.hpp"; + auto capture = f.take({{file, true, true}}); + require(capture.has_value()); + expect((*capture)->entries().front().node == SourceNode::missing); + fs::create_directory(dir); + failed(f.catalog.validate(f.scope, **capture), SourceIssue::changed); + failed(f.take({{file, true}}), SourceIssue::missing_parent); + require(f.open(file, "unsaved").has_value()); + failed(f.take({{file, true, true}}), SourceIssue::missing_parent); +} + +VOID_TEST(SourceCatalogTests, captures_disk_and_unsaved_source_in_request_order) { + Files f; + const auto source = f.root / "source.cpp", header = f.root / "nested" / "α.hpp"; + Files::write(source, "saved"); + Files::write(header, "disk header"); + auto overlay = f.open(header, ""); + require(overlay.has_value()); + AccessWatch watch(header); + auto cap = f.take({{header}, {source}, {header}}); + require(cap.has_value()); + auto entries = (*cap)->entries(); + require(entries.size() == 3); + expect(entries[0].snapshot == *overlay && entries[2].snapshot == *overlay); + expect(entries[1].snapshot->text == "saved"); + expect(entries[1].snapshot->origin == D::DocumentOrigin::disk); + expect(entries[0].logical_path == header && + entries[0].snapshot->identity.canonical_path == header); + expect(!watch.accessed()); + expect(f.catalog.validate(f.scope, **cap).has_value()); +} + +VOID_TEST(SourceCatalogTests, absent_optional_leaf_becomes_an_unsaved_then_a_saved_header) { + Files f; + auto header = f.root / "absent.hpp"; + failed(f.take({{header}}), SourceIssue::missing); + auto old = f.take({{header, true}}); + require(old.has_value()); + expect(!(*old)->entries()[0].snapshot); + require(f.open(header, "new overlay").has_value()); + failed(f.catalog.validate(f.scope, **old), SourceIssue::changed); + auto unsaved = f.take({{header}}); + require(unsaved.has_value()); + expect((*unsaved)->entries()[0].snapshot->text == "new overlay"); + require(f.documents.close(D::path_to_file_uri(header)).has_value()); + auto absent = f.take({{header, true}}); + require(absent.has_value()); + Files::write(header, "new disk"); + failed(f.catalog.validate(f.scope, **absent), SourceIssue::changed); + fs::remove(header); + failed(f.catalog.validate(f.scope, **absent), SourceIssue::changed); + expect((*unsaved)->entries()[0].snapshot->text == "new overlay"); +} + +VOID_TEST(SourceCatalogTests, binds_job_and_installed_grants_before_reading_shared_files) { + Files f; + const auto path = f.external / "shared.hpp"; + Files::write(path, "shared"); + const auto first = f.install({f.root, f.external}); + SourceScope other{{f.root, "another-incarnation"}, f.scope.configuration, f.scope.trust}; + const auto requests = std::array{SourceRequest{path}}; + AccessWatch watch(path); + auto attempt = [&](const SourceScope &scope, const InstalledSourceGrant &grant) { + return f.catalog.capture(scope, grant, f.census(), requests); + }; + failed(attempt(other, first), SourceIssue::wrong_authority); + auto old_settings = f.scope; + ++old_settings.configuration; + failed(attempt(old_settings, first), SourceIssue::wrong_authority); + auto old_trust = f.scope; + ++old_trust.trust; + failed(attempt(old_trust, first), SourceIssue::wrong_authority); + f.catalog.revoke(); + const auto renewed = f.install({f.root, f.external}); + failed(attempt(f.scope, first), SourceIssue::wrong_authority); + expect(!watch.accessed()); + require(attempt(f.scope, renewed).has_value()); + expect(watch.accessed()); +} + +VOID_TEST(SourceCatalogTests, retains_the_callers_empty_census_and_only_the_selected_text) { + Files f; + const auto tu = f.root / "tu.cpp", header = f.root / "new.hpp"; + Files::write(tu, "tu"); + const auto before = f.census(); + auto overlay = f.open(header, "unsaved"); + require(overlay.has_value()); + std::weak_ptr unrelated = *overlay; + overlay->reset(); + auto requests = std::array{SourceRequest{tu}}; + AccessWatch watch(tu); + failed(f.catalog.capture(f.scope, f.grant, before, requests), SourceIssue::changed); + expect(!watch.accessed()); + auto selected = f.take({{tu}}); + require(selected.has_value()); + require(f.documents.close(D::path_to_file_uri(header)).has_value()); + expect(unrelated.expired()); + failed(f.catalog.validate(f.scope, **selected), SourceIssue::changed); +} + +VOID_TEST(SourceCatalogTests, refuses_a_desynchronized_or_refused_overlay_without_reading_disk) { + D::DocumentLimits limits; + limits.max_open_documents = 1; + Files f{{}, limits}; + const auto a = f.root / "a.cpp", b = f.root / "b.cpp"; + Files::write(a, "disk-a"); + Files::write(b, "disk-b"); + require(f.open(a, "open").has_value()); + require(!f.open(b, "refused").has_value()); + AccessWatch first(a), second(b); + require(f.documents + .mark_desynchronized(D::path_to_file_uri(a), 2, + {D::DocumentError::Kind::malformed_change, "bad edit"}) + .has_value()); + failed(f.take({{a}}), SourceIssue::unavailable_overlay); + failed(f.take({{b}}), SourceIssue::unavailable_overlay); + expect(!first.accessed() && !second.accessed()); +} + +VOID_TEST(SourceCatalogTests, rejects_another_editor_stores_census_before_disk_access) { + Files f; + const auto source = f.root / "edited.cpp"; + Files::write(source, "disk"); + require(f.open(source, "editor").has_value()); + D::DocumentStore different_editor; + auto empty = different_editor.file_overlay_inventory(); + require(empty.has_value()); + AccessWatch watch(source); + const std::array requests{SourceRequest{source}}; + failed(f.catalog.capture(f.scope, f.grant, *empty, requests), SourceIssue::changed); + auto correct = f.take({{source}}); + require(correct.has_value()); + expect((*correct)->entries()[0].snapshot->text == "editor"); + expect(!watch.accessed()); +} + +VOID_TEST(SourceCatalogTests, refuses_two_open_uri_aliases_for_one_physical_source) { + Files f; + auto path = f.root / "target.cpp", alias = f.root / "alias.cpp"; + Files::write(path, "disk"); + fs::create_symlink(path, alias); + require(f.open(path, "one").has_value()); + require(f.open(alias, "two").has_value()); + failed(f.take({{path}}), SourceIssue::unavailable_overlay); +} + +VOID_TEST(SourceCatalogTests, invalidates_identical_bytes_on_leaf_and_directory_replacement) { + Files f; + auto parent = f.root / "nested", path = parent / "a.cpp"; + Files::write(path, "stable"); + f.grant = f.install({f.root, parent, f.external}); + auto old = f.take({{path}}); + require(old.has_value()); + Files::write(parent / "new", "stable"); + fs::rename(parent / "new", path); + failed(f.catalog.validate(f.scope, **old), SourceIssue::changed); + auto fresh = f.take({{path}}); + require(fresh.has_value()); + fs::rename(parent, f.root / "old"); + fs::create_directory(parent); + Files::write(path, "new"); + failed(f.catalog.validate(f.scope, **fresh), SourceIssue::changed); + failed(f.take({{path}}), SourceIssue::changed); + expect((*old)->entries()[0].snapshot->text == "stable"); +} + +VOID_TEST(SourceCatalogTests, replacement_of_the_workspace_invalidates_an_external_only_capture) { + Files f; + f.grant = f.install({f.external}); + const auto path = f.external / "header.hpp"; + Files::write(path, "header"); + auto old = f.take({{path}}); + require(old.has_value()); + fs::rename(f.root, f.external.parent_path() / "old-workspace"); + fs::create_directory(f.root); + failed(f.catalog.validate(f.scope, **old), SourceIssue::changed); + failed(f.take({{path}}), SourceIssue::changed); +} + +VOID_TEST(SourceCatalogTests, refuses_hard_links_and_special_files_before_reading) { + Files f; + const auto primary = f.root / "public.hpp", other = f.root / "impl.hpp"; + Files::write(primary, "stale"); + fs::create_hard_link(primary, other); + require(f.open(other, "").has_value()); + AccessWatch watch(primary); + failed(f.take({{primary}}), SourceIssue::hard_link); + expect(!watch.accessed()); + const auto fifo = f.root / "fifo"; + require(::mkfifo(fifo.c_str(), 0600) == 0); + failed(f.take({{fifo}}), SourceIssue::not_regular); + failed(f.take({{f.root / "nested"}}), SourceIssue::not_regular); +} + +VOID_TEST(SourceCatalogTests, refuses_unsupported_and_outside_routes_before_source_reads) { + Files f; + auto outside = f.external / "secret.hpp", link = f.root / "leaf", dir = f.root / "dir"; + Files::write(outside, "benign external fixture"); + fs::create_symlink(outside, link); + fs::create_directory_symlink(f.external, dir); + AccessWatch watch(outside); + failed(f.take({{outside}}), SourceIssue::outside_scope); + failed(f.take({{link, true}}), SourceIssue::unsupported_route); + failed(f.take({{dir / "secret.hpp", true}}), SourceIssue::unsupported_route); + failed(f.take({{f.root / "nested" / ".." / "leaf"}}), SourceIssue::invalid_path); + failed(f.take({{f.root / "missing" / "a.hpp", true}}), SourceIssue::missing_parent); + expect(!watch.accessed()); +} + +VOID_TEST(SourceCatalogTests, + rejects_conflicting_ancestor_and_descendant_file_names_in_either_order) { + Files f; + auto parent = f.root / "generated", child = parent / "config.hpp"; + require(f.open(child, "unsaved").has_value()); + failed(f.take({{parent, true}, {child}}), SourceIssue::conflicting_names); + failed(f.take({{child}, {parent, true}}), SourceIssue::conflicting_names); + require(f.open(parent, "separate file").has_value()); + failed(f.take({{parent}, {child}}), SourceIssue::conflicting_names); + failed(f.take({{child}, {parent}}), SourceIssue::conflicting_names); +} + +VOID_TEST(SourceCatalogTests, validates_authority_editor_and_disk_again_after_capture) { + std::function change; + Files f{[&] { + if (change) + change(); + }}; + const auto path = f.root / "a.cpp"; + Files::write(path, "before"); + change = [&] { Files::write(path, "after"); }; + failed(f.take({{path}}), SourceIssue::changed); + change = [&] { require(f.open(path, "now unsaved").has_value()); }; + failed(f.take({{path}}), SourceIssue::changed); + change = [&] { + std::array edits{D::TextEdit{std::nullopt, "later"}}; + require(f.documents.apply_changes(D::path_to_file_uri(path), 2, edits).has_value()); + }; + failed(f.take({{path}}), SourceIssue::changed); + change = [&] { f.catalog.revoke(); }; + failed(f.take({{path}}), SourceIssue::wrong_authority); +} + +VOID_TEST(SourceCatalogTests, enforces_count_bytes_descriptors_and_retained_capture_limits) { + Files f; + auto a = f.root / "a.cpp", b = f.root / "nested" / "b.hpp"; + Files::write(a, "abc"); + Files::write(b, "defg"); + failed(f.take({{a}, {b}}, {.files = 1}), SourceIssue::resource_limit); + failed(f.take({{a}}, {.name_bytes = 1}), SourceIssue::resource_limit); + failed(f.take({{a}}, {.file_bytes = 2}), SourceIssue::resource_limit); + failed(f.take({{a}, {b}}, {.total_bytes = 6}), SourceIssue::resource_limit); + failed(f.take({{b}}, {.descriptors = 1}), SourceIssue::resource_limit); + require(f.take({{a}, {b}}, {.total_bytes = 7}).has_value()); + std::vector> retained; + for (unsigned i = 0; i < 63; ++i) { + auto cap = f.take({{a}}); + require(cap.has_value()); + retained.push_back(std::move(*cap)); + } + failed(f.take({{a}}), SourceIssue::resource_limit); + retained.pop_back(); + expect(f.take({{a}}).has_value()); +} diff --git a/tests/workspace/ProviderSessionTests.cpp b/tests/workspace/ProviderSessionTests.cpp new file mode 100644 index 0000000..66c95a9 --- /dev/null +++ b/tests/workspace/ProviderSessionTests.cpp @@ -0,0 +1,556 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +namespace Workspace = Void::LanguageServer::Workspace; +namespace Docs = Void::LanguageServer::Documents; +namespace Protocol = Void::LanguageServer::Protocol; +using Protocol::Json; +using Void::Testing::expect; +using Void::Testing::require; +using namespace std::chrono_literals; + +Json str(std::string_view value) { return Json{std::string{value}}; } +Json integer(std::int64_t value) { return Json{value}; } +Json object(Json::Object fields = {}) { return Json{std::move(fields)}; } +Json uri(const fs::path &path) { return Json{Docs::path_to_file_uri(path)}; } + +const Json *field(const Json &value, std::string_view name) { + const auto *fields = Protocol::as_object(&value); + return fields ? Protocol::find_member(*fields, name) : nullptr; +} + +std::string read_string(const Json &value, std::string_view name) { + const auto *text = Protocol::as_string(field(value, name)); + require(text != nullptr); + return *text; +} + +const Json &nested(const Json &value, std::string_view name) { + const auto *entry = field(value, name); + require(entry != nullptr); + return *entry; +} + +std::string issue(const Json &value) { + const auto *issues = Protocol::as_array(field(value, "issues")); + require(issues && !issues->empty()); + return read_string(issues->front(), "code"); +} + +Json folder(const fs::path &root) { return object({{"uri", uri(root)}, {"name", str("C++")}}); } + +Json initialize(Json::Array roots, Json settings = object()) { + return object( + {{"workspaceFolders", Json{std::move(roots)}}, + {"initializationOptions", object({{"voidLanguageServer", std::move(settings)}})}}); +} + +Json change(Json::Array added, Json::Array removed) { + auto event = object({{"added", Json{std::move(added)}}, {"removed", Json{std::move(removed)}}}); + return object({{"event", std::move(event)}}); +} + +Json configuration(Json::Object entries) { + return object({{"settings", object({{"voidLanguageServer", object(std::move(entries))}})}}); +} + +Json query(const fs::path &root = {}, const fs::path &file = {}) { + Json::Object params; + if (!root.empty()) + params.emplace("workspaceUri", uri(root)); + if (!file.empty()) + params.emplace("textDocument", object({{"uri", uri(file)}})); + return object(std::move(params)); +} + +Json status(vls::WorkspaceSession &session, const Json ¶ms = object()) { + auto result = session.provider_status(¶ms); + require(result.has_value()); + auto wire = Protocol::serialize_json(*result); + require(wire.has_value()); + expect(wire->size() < 512 * 1024); + return std::move(*result); +} + +void write(const fs::path &path, std::string_view text) { + fs::create_directories(path.parent_path()); + std::ofstream file{path, std::ios::binary}; + file << text; + file.close(); + require(file.good()); +} + +void write_json(const fs::path &path, const Json &value) { + auto text = Protocol::serialize_json(value); + require(text.has_value()); + write(path, *text); +} + +struct Fixture { + Void::FileSystem::TempDir temp{"vls_provider_session_"}; + fs::path base = fs::canonical(temp.path()); + fs::path one = base / "one", two = base / "one-more", external = base / "external"; + Fixture() { + write(one / "main.cpp", "int one;\n"); + write(two / "main.cpp", "int two;\n"); + fs::create_directories(external); + } + + static void compdb(const fs::path &root, const fs::path &path, unsigned count = 1, + std::string_view compiler = "g++") { + Json::Array records; + for (auto i = 0U; i < count; ++i) { + records.push_back( + object({{"directory", Json{root.native()}}, + {"file", str("main.cpp")}, + {"arguments", Json{Json::Array{str(compiler), str("-c"), str("main.cpp"), + Json{"-DCASE=" + std::to_string(i)}}}}})); + } + write_json(path, Json{std::move(records)}); + } + + static fs::path native(const fs::path &root, const fs::path &build, unsigned count = 1, + const fs::path &selector = {}) { + constexpr std::string_view id = "0123456789abcdef"; + const auto editor = build / "profiles/debug/editor"; + const auto database = editor / "generations" / id / "compile_commands.json"; + compdb(root, database, count); + write_json(editor / "status.json", object({{"schema_version", integer(1)}, + {"profile", str("debug")}, + {"status", str("valid")}, + {"diagnostic", str("")}, + {"generation_id", str(id)}, + {"compdb_path", Json{database.native()}}, + {"entry_count", integer(count)}, + {"readiness_warnings", Json{Json::Array{}}}})); + write_json(selector.empty() ? root / ".vbs/editor_selection.json" : selector, + object({{"schema_version", integer(1)}, + {"ticket", integer(7)}, + {"selected_profile", str("debug")}, + {"selected_build_root", Json{build.native()}}, + {"selected_generation_id", str(id)}, + {"selected_compdb_path", Json{database.native()}}})); + return database; + } +}; + +struct PauseObservation { + std::atomic_bool pause_next{}; + std::binary_semaphore paused{0}, resume{0}; + + void hook() { + if (pause_next.exchange(false)) { + paused.release(); + resume.acquire(); + } + } + + template + Json run(vls::WorkspaceSession &session, F action, const Json ¶ms = object()) { + pause_next = true; + auto old = std::async(std::launch::async, [&] { return status(session, params); }); + { + struct Resume { + std::binary_semaphore &gate; + ~Resume() { gate.release(); } + } release{resume}; + require(paused.try_acquire_for(5s)); + action(); + } + return old.get(); + } +}; +} // namespace + +VOID_TEST(ProviderSession, workspace_folders_precedence_and_legacy_root) { + Fixture f; + vls::WorkspaceSession absent, empty, explicit_null, legacy, invalid; + require(absent.initialize(object()).has_value()); + require(empty + .initialize(object({{"workspaceFolders", Json{Json::Array{}}}, + {"rootUri", str("invalid but unused")}})) + .has_value()); + require(explicit_null + .initialize(object({{"workspaceFolders", Json{nullptr}}, {"rootUri", uri(f.one)}})) + .has_value()); + for (auto *session : {&absent, &empty, &explicit_null}) + expect(read_string(status(*session), "state") == "documentOnly"); + require(legacy.initialize(object({{"rootUri", uri(f.one)}})).has_value()); + const auto legacy_status = status(legacy); + expect(read_string(legacy_status, "workspaceUri") == Docs::path_to_file_uri(f.one)); + expect(read_string(legacy_status, "state") == "missing"); + expect(!invalid.initialize(object({{"rootUri", str("file://remote/tmp")}}))); + expect(!invalid.initialize(initialize({folder(f.one / "main.cpp")}))); + expect(!invalid.initialize(initialize({folder(f.base / "absent" / ".." / "one")}))); + expect(!invalid.initialize(initialize(Json::Array(65, folder(f.one))))); + fs::create_directory_symlink(f.one, f.base / "alias"); + expect(!invalid.initialize(initialize({folder(f.one), folder(f.base / "alias")}))); + require(invalid.initialize(initialize({folder(f.base / "alias")})).has_value()); + expect(read_string(status(invalid, query(f.base / "alias")), "workspaceUri") == + Docs::path_to_file_uri(f.one)); + fs::remove(f.base / "alias"); + fs::create_directory(f.base / "alias"); + fs::create_directory_symlink(f.base / "alias", f.base / "other-alias"); + auto colliding = change({folder(f.base / "other-alias")}, {}); + expect(!invalid.update_folders(&colliding)); + expect(read_string(status(invalid, query(f.base / "alias")), "workspaceUri") == + Docs::path_to_file_uri(f.one)); + const auto virtual_query = + object({{"textDocument", object({{"uri", str("untitled:buffer")}})}}); + expect(read_string(status(invalid, virtual_query), "state") == "documentOnly"); +} + +VOID_TEST(ProviderSession, independent_roots_and_deterministic_contexts) { + Fixture f; + f.native(f.one, f.one / "build", 20); + f.compdb(f.two, f.two / "editor/build.json", 2); + const auto settings = + object({{"selectedProfile", str("debug")}, + {"workspaces", object({{Docs::path_to_file_uri(f.two), + object({{"provider", str("compdb")}, + {"compdbPath", str("editor/build.json")}})}})}}); + vls::WorkspaceSession session; + require(session.initialize(initialize({folder(f.one), folder(f.two)}, settings)).has_value()); + expect(!session.provider_status(nullptr)); + const auto first = status(session, query({}, f.one / "main.cpp")); + const auto second = status(session, query({}, f.two / "main.cpp")); + expect(read_string(first, "provider") == "vbs" && read_string(first, "state") == "ready"); + expect(read_string(first, "nativeGeneration") == "0123456789abcdef"); + expect(Protocol::as_int64(field(first, "ticket")) == 7); + expect(Protocol::as_int64(field(first, "contextCount")) == 20); + expect(Protocol::as_bool(field(first, "alternativesTruncated")) == true); + expect(read_string(nested(first, "selected"), "profile") == "debug"); + expect(read_string(nested(first, "selected"), "owningTu") == + Docs::path_to_file_uri(f.one / "main.cpp")); + expect(read_string(second, "provider") == "compdb" && read_string(second, "state") == "ready"); + expect(read_string(first, "incarnation") != read_string(second, "incarnation")); + const auto *alternatives = Protocol::as_array(field(second, "alternatives")); + require(alternatives && alternatives->size() == 2); + const auto selected = read_string(nested(second, "selected"), "alternative"); + expect(selected == read_string(alternatives->front(), "alternative")); + const auto again = status(session, query(f.two, f.two / "main.cpp")); + expect(read_string(nested(again, "selected"), "alternative") == selected); + + fs::create_directories(f.one / "nested"); + auto added = change({folder(f.one / "nested")}, {}); + require(session.update_folders(&added).has_value()); + auto ambiguous = query({}, f.one / "nested/main.cpp"); + expect(!session.provider_status(&ambiguous)); + expect(read_string(status(session, query(f.one, f.one / "nested/main.cpp")), "state") == + "ready"); +} + +VOID_TEST(ProviderSession, malformed_updates_preserve_roots_settings_and_history) { + Fixture f; + const auto database = f.one / "compile_commands.json"; + f.compdb(f.one, database); + vls::WorkspaceSession session; + require(session.initialize(initialize({folder(f.one), folder(f.two)})).has_value()); + const auto valid = status(session, query(f.one)); + auto bad_configuration = configuration( + {{"provider", str("none")}, + {"workspaces", + object({{Docs::path_to_file_uri(f.two), object({{"selectedProfile", integer(2)}})}})}}); + expect(!session.configure(&bad_configuration)); + auto bad_folders = change({folder(f.external / "absent")}, {folder(f.one)}); + expect(!session.update_folders(&bad_folders)); + auto malformed = object({{"workspaceUri", integer(5)}}); + expect(!session.provider_status(&malformed)); + write(database, "invalid"); + const auto degraded = status(session, query(f.one)); + expect(read_string(degraded, "state") == "degraded"); + expect(read_string(degraded, "incarnation") == read_string(valid, "incarnation")); + expect(read_string(nested(degraded, "lastGood"), "generation") == + read_string(valid, "generation")); + expect(!field(degraded, "generation")); + + auto disable_two = configuration( + {{"workspaces", + object({{Docs::path_to_file_uri(f.two), object({{"provider", str("none")}})}})}}); + require(session.configure(&disable_two).has_value()); + expect(read_string(status(session, query(f.two)), "state") == "disabled"); + expect(read_string(status(session, query(f.one)), "state") == "degraded"); +} + +VOID_TEST(ProviderSession, broken_native_authority_suppresses_automatic_fallback) { + Fixture f; + f.compdb(f.one, f.one / "compile_commands.json"); + const auto selector = f.one / ".vbs/editor_selection.json"; + vls::WorkspaceSession session; + require(session.initialize(initialize({folder(f.one)})).has_value()); + expect(read_string(status(session), "provider") == "compdb"); + + auto vbs = configuration({{"provider", str("vbs")}}); + require(session.configure(&vbs).has_value()); + const auto missing = status(session); + expect(read_string(missing, "provider") == "vbs" && read_string(missing, "state") == "missing"); + auto automatic = configuration({}); + require(session.configure(&automatic).has_value()); + fs::create_directories(selector.parent_path()); + fs::create_symlink(f.one / "absent.json", selector); + const auto denied = status(session); + expect(read_string(denied, "provider") == "vbs" && issue(denied) == "outside_scope"); + fs::remove(selector); + write(selector, "{"); + const auto corrupt = status(session); + expect(read_string(corrupt, "provider") == "vbs" && issue(corrupt) == "invalid_metadata"); + const auto build = f.one / "build"; + const auto db = f.native(f.one, build); + auto status_path = build / "profiles/debug/editor/status.json"; + fs::remove(status_path); + const auto unavailable = status(session); + expect(read_string(unavailable, "provider") == "vbs" && + issue(unavailable) == "missing_reference"); + f.native(f.one, build); + const auto ready = status(session); + write_json(status_path, object({{"schema_version", integer(1)}, + {"profile", str("debug")}, + {"status", str("valid")}, + {"diagnostic", str("")}, + {"generation_id", str("1123456789abcdef")}, + {"compdb_path", Json{db.native()}}, + {"entry_count", integer(1)}, + {"readiness_warnings", Json{Json::Array{}}}})); + const auto mismatch = status(session); + expect(read_string(mismatch, "state") == "stale" && issue(mismatch) == "generation_mismatch"); + write_json(status_path, object({{"schema_version", integer(1)}, + {"profile", str("debug")}, + {"status", str("stale")}, + {"diagnostic", str("build failed")}})); + const auto stale = status(session); + expect(read_string(stale, "state") == "stale" && issue(stale) == "vbs_stale"); + expect(read_string(nested(stale, "lastGood"), "generation") == + read_string(ready, "generation")); + fs::remove(db); + auto compdb = configuration({{"provider", str("compdb")}}); + require(session.configure(&compdb).has_value()); + expect(read_string(status(session), "provider") == "compdb"); +} + +VOID_TEST(ProviderSession, managed_native_aliases_are_ineligible_for_automatic_compdb) { + Fixture f; + const auto build = f.one / "out"; + const auto generation = f.native(f.one, build); + fs::remove(f.one / ".vbs/editor_selection.json"); + vls::WorkspaceSession session; + require(session.initialize(initialize({folder(f.one)})).has_value()); + for (const auto *relative : {"compile_commands.json", "out/compile_commands.json", + "out/profiles/debug/editor/compile_commands.json"}) { + fs::create_symlink(generation, f.one / relative); + auto config = configuration({{"compdbPath", str(relative)}}); + require(session.configure(&config).has_value()); + const auto result = status(session); + expect(read_string(result, "state") == "degraded" && issue(result) == "vbs_managed_alias"); + expect(!field(result, "generation")); + } + auto manual = configuration( + {{"provider", str("compdb")}, {"compdbPath", str("out/compile_commands.json")}}); + require(session.configure(&manual).has_value()); + expect(read_string(status(session), "state") == "ready"); +} + +VOID_TEST(ProviderSession, passive_commands_never_execute_and_launcher_grants_stay_root_bound) { + Fixture f; + const auto tool = f.one / "marker-tool"; + const auto marker = f.one / "ran"; + write(tool, "#!/bin/sh\n: > '" + marker.native() + "'\n"); + fs::permissions(tool, fs::perms::owner_read | fs::perms::owner_write | fs::perms::owner_exec); + const auto database = f.external / "selected.json"; + f.compdb(f.one, database, 1, tool.native()); + Workspace::SettingsOverrides flags; + flags.compdb_path = database; + flags.tool_approvals = {{f.one, Workspace::AuthorityLevel::compiler_use, tool}}; + vls::WorkspaceSession session( + {.root = f.one, .cli_settings = Workspace::settings_from_cli(flags, f.base)}); + auto settings = object({{"provider", str("compdb")}, + {"compdbPath", Json{database.native()}}, + {"allowExplicitBuildActions", Json{true}}}); + require(session.initialize(initialize({folder(f.one), folder(f.two)}, settings)).has_value()); + expect(read_string(status(session, query(f.one)), "state") == "ready"); + const auto denied = status(session, query(f.two)); + expect(read_string(denied, "state") == "degraded" && issue(denied) == "outside_scope"); + expect(!fs::exists(marker)); +} + +VOID_TEST(ProviderSession, launcher_anchors_survive_configuration_and_root_readdition) { + Fixture f; + const auto database = f.external / "chosen.json"; + f.compdb(f.one, database); + Workspace::SettingsOverrides flags{.provider = Workspace::ProviderPreference::compdb, + .compdb_path = database}; + vls::WorkspaceSession session( + {.root = f.one, .cli_settings = Workspace::settings_from_cli(flags, f.base)}); + require(session.initialize(initialize({folder(f.one)})).has_value()); + const auto initial = status(session); + auto replacement = database.parent_path() / "replacement.json"; + f.compdb(f.one, replacement, 2); + fs::rename(replacement, database); + const auto good = status(session); + expect(read_string(good, "generation") != read_string(initial, "generation")); + + // The next launcher receives exactly this directory, which will be replaced before init. + vls::WorkspaceSession before_init( + {.root = f.one, .cli_settings = Workspace::settings_from_cli(flags, f.base)}); + fs::rename(f.external, f.base / "retired-external"); + f.compdb(f.one, database, 3); + auto config = configuration({{"selectedProfile", str("debug")}}); + require(session.configure(&config).has_value()); + const auto replaced = status(session); + expect(read_string(replaced, "state") == "stale" && !field(replaced, "generation")); + expect(read_string(nested(replaced, "lastGood"), "generation") == + read_string(good, "generation")); + auto reincarnate = change({folder(f.one)}, {folder(f.one)}); + require(session.update_folders(&reincarnate).has_value()); + const auto readded = status(session); + expect(read_string(readded, "state") == "stale" && issue(readded) == "changed"); + expect(read_string(readded, "incarnation") != read_string(good, "incarnation")); + expect(!field(readded, "lastGood") && !field(readded, "generation")); + require(before_init.initialize(initialize({folder(f.one)})).has_value()); + const auto initially_replaced = status(before_init); + expect(read_string(initially_replaced, "state") == "stale" && + issue(initially_replaced) == "changed"); + expect(!field(initially_replaced, "generation") && !field(initially_replaced, "lastGood")); +} + +VOID_TEST(ProviderSession, selector_appearance_invalidates_successful_fallback) { + Fixture f; + f.compdb(f.one, f.one / "compile_commands.json"); + PauseObservation gate; + vls::WorkspaceSession session({}, [&] { gate.hook(); }); + require(session.initialize(initialize({folder(f.one)})).has_value()); + const auto discarded = gate.run(session, [&] { f.native(f.one, f.one / "native"); }); + expect(read_string(discarded, "state") == "stale" && issue(discarded) == "inputs_changed"); + expect(!field(discarded, "generation") && !field(discarded, "lastGood")); + const auto ready = status(session); + expect(read_string(ready, "provider") == "vbs" && read_string(ready, "state") == "ready"); +} + +VOID_TEST(ProviderSession, appearing_native_status_and_replaced_db_invalidate_old_reads) { + Fixture f; + auto build = f.one / "native"; + auto database = f.native(f.one, build); + const auto profile_status = build / "profiles/debug/editor/status.json"; + fs::rename(profile_status, f.base / "saved.json"); + PauseObservation gate; + vls::WorkspaceSession session({}, [&] { gate.hook(); }); + require(session.initialize(initialize({folder(f.one)})).has_value()); + auto stale = gate.run(session, [&] { fs::rename(f.base / "saved.json", profile_status); }); + expect(issue(stale) == "inputs_changed"); + const auto ready = status(session); + expect(read_string(ready, "state") == "ready"); + stale = gate.run(session, [&] { write(database, "invalid"); }); + expect(issue(stale) == "inputs_changed" && !field(stale, "generation")); + expect(read_string(nested(stale, "lastGood"), "generation") == + read_string(ready, "generation")); +} + +VOID_TEST(ProviderSession, changing_the_queried_alias_invalidates_an_inflight_selection) { + Fixture f; + f.compdb(f.one, f.one / "compile_commands.json"); + const auto alias = f.one / "alias.cpp"; + write(f.one / "other.cpp", "int other;\n"); + fs::create_symlink("main.cpp", alias); + PauseObservation gate; + vls::WorkspaceSession session({}, [&] { gate.hook(); }); + require(session.initialize(initialize({folder(f.one)})).has_value()); + const auto params = query(f.one, alias); + const auto initial = status(session, params); + expect(read_string(nested(initial, "selected"), "owningTu") == + Docs::path_to_file_uri(f.one / "main.cpp")); + const auto stale = gate.run( + session, + [&] { + fs::remove(alias); + fs::create_symlink("other.cpp", alias); + }, + params); + expect(issue(stale) == "inputs_changed" && !field(stale, "generation")); + expect( + std::holds_alternative(nested(status(session, params), "selected").value)); +} + +VOID_TEST(ProviderSession, newer_success_and_failure_displace_older_observations) { + Fixture f; + const auto database = f.one / "compile_commands.json"; + f.compdb(f.one, database); + PauseObservation gate; + vls::WorkspaceSession session({}, [&] { gate.hook(); }); + require(session.initialize(initialize({folder(f.one)})).has_value()); + const auto first = status(session); + // Both snapshots are good and use the same file identities. Sequence alone displaces the first. + auto stale = + gate.run(session, [&] { expect(read_string(status(session), "state") == "ready"); }); + expect(issue(stale) == "superseded"); + + f.compdb(f.one, database, 2); + stale = gate.run(session, [&] { + write(database, "invalid"); + expect(read_string(status(session), "state") == "degraded"); + }); + expect(issue(stale) == "superseded"); + expect(read_string(nested(status(session), "lastGood"), "generation") == + read_string(first, "generation")); + + stale = gate.run(session, [&] { + f.compdb(f.one, database, 3); + expect(read_string(status(session), "state") == "ready"); + }); + expect(issue(stale) == "superseded"); + const auto last = status(session); + write(database, "invalid"); + expect(read_string(nested(status(session), "lastGood"), "generation") == + read_string(last, "generation")); +} + +VOID_TEST(ProviderSession, configuration_revocation_and_incarnation_reject_late_work) { + Fixture f; + f.compdb(f.one, f.one / "compile_commands.json"); + f.compdb(f.one, f.one / "different.json", 2); + Workspace::SettingsOverrides flags; + flags.tool_approvals = { + {f.one, Workspace::AuthorityLevel::compiler_use, f.one / "marker-tool"}}; + PauseObservation gate; + vls::WorkspaceSession session( + {.root = f.one, .cli_settings = Workspace::settings_from_cli(flags, f.base)}, + [&] { gate.hook(); }); + require(session.initialize(initialize({folder(f.one)})).has_value()); + + auto stale = gate.run(session, [&] { + auto config = configuration({{"compdbPath", str("different.json")}}); + require(session.configure(&config).has_value()); + }); + expect(issue(stale) == "superseded" && !field(stale, "lastGood")); + const auto ready = status(session); + expect(Protocol::as_int64(field(ready, "contextCount")) == 2); + + stale = gate.run(session, [&] { session.revoke_root_authority(f.one); }); + expect(issue(stale) == "superseded" && !field(stale, "generation")); + + std::string new_incarnation; + stale = gate.run(session, [&] { + auto removed = change({}, {folder(f.one)}); + require(session.update_folders(&removed).has_value()); + expect(read_string(status(session), "state") == "documentOnly"); + auto added = change({folder(f.one)}, {}); + require(session.update_folders(&added).has_value()); + new_incarnation = read_string(status(session), "incarnation"); + }); + expect(issue(stale) == "superseded" && !field(stale, "lastGood")); + expect(read_string(stale, "incarnation") == read_string(ready, "incarnation")); + expect(read_string(stale, "incarnation") != new_incarnation); + expect(read_string(status(session), "incarnation") == new_incarnation); +} diff --git a/tests/workspace/SemanticLeaseTests.cpp b/tests/workspace/SemanticLeaseTests.cpp new file mode 100644 index 0000000..7bd155b --- /dev/null +++ b/tests/workspace/SemanticLeaseTests.cpp @@ -0,0 +1,589 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +namespace Build = Void::LanguageServer::Build; +namespace Docs = Void::LanguageServer::Documents; +namespace Protocol = Void::LanguageServer::Protocol; +namespace Workspace = Void::LanguageServer::Workspace; +using Protocol::Json; +using vls::SemanticContextIssue; +using vls::SemanticContextLease; +using vls::SemanticDriver; +using vls::WorkspaceSession; +using Void::Testing::expect; +using Void::Testing::require; +using Strings = std::vector; +using namespace std::chrono_literals; +using namespace std::string_view_literals; + +template T take(std::expected result) { + require(result.has_value()); + return std::move(*result); +} + +void write_file(const fs::path &path, std::string_view bytes) { + fs::create_directories(path.parent_path()); + std::ofstream file{path, std::ios::binary}; + file << bytes; + file.close(); + require(file.good()); +} + +void write_json(const fs::path &path, const Json &json) { + write_file(path, take(Protocol::serialize_json(json))); +} + +const Json &field(const Json &json, std::string_view key) { + const auto *object = Protocol::as_object(&json); + require(object != nullptr); + const auto *value = Protocol::find_member(*object, key); + require(value != nullptr); + return *value; +} + +std::string text(const Json &json, std::string_view key) { + const auto *value = Protocol::as_string(&field(json, key)); + require(value != nullptr); + return *value; +} + +Json object(Json::Object fields) { return Json{std::move(fields)}; } +Json str(std::string_view value) { return Json{std::string{value}}; } +Json folder(const fs::path &root) { return object({{"uri", str(Docs::path_to_file_uri(root))}}); } + +void initialize(WorkspaceSession &session, const fs::path &root, Json settings = object({})) { + auto params = + object({{"workspaceFolders", Json{Json::Array{folder(root)}}}, + {"initializationOptions", object({{"voidLanguageServer", std::move(settings)}})}}); + require(session.initialize(params).has_value()); +} + +void update(WorkspaceSession &session, Json::Array add, Json::Array remove) { + auto event = object({{"added", Json{std::move(add)}}, {"removed", Json{std::move(remove)}}}); + auto params = object({{"event", std::move(event)}}); + require(session.update_folders(¶ms).has_value()); +} + +Json status(WorkspaceSession &session, const fs::path &root, const fs::path &file) { + const auto params = object( + {{"workspaceUri", str(Docs::path_to_file_uri(root))}, {"textDocument", folder(file)}}); + return take(session.provider_status(¶ms)); +} + +auto acquire(WorkspaceSession &session, const fs::path &file, const SemanticDriver &driver, + const fs::path &workspace = {}) { + const auto uri = Docs::path_to_file_uri(workspace); + return session.acquire_semantic_context( + Docs::path_to_file_uri(file), + workspace.empty() ? std::nullopt : std::optional{uri}, driver); +} + +template +void fails(const std::expected &result, SemanticContextIssue issue) { + require(!result.has_value()); + expect(result.error().issue == issue); + expect(!result.error().message.empty()); +} + +struct Gate { + std::atomic_bool armed{}; + std::binary_semaphore entered{0}, resume{0}; + + void hook() { + if (armed.exchange(false)) { + entered.release(); + resume.acquire(); + } + } + + template + auto during(Operation operation, Mutation mutation) { + armed = true; + auto pending = std::async(std::launch::async, std::move(operation)); + { + struct Release { + std::binary_semaphore &semaphore; + ~Release() { semaphore.release(); } + } release{resume}; + require(entered.try_acquire_for(5s)); + mutation(); + } + return pending.get(); + } +}; + +struct Fixture { + Void::FileSystem::TempDir temporary{"vls_semantic_lease_"}; + fs::path base = fs::canonical(temporary.path()), root = base / "workspace"; + fs::path a = root / "src/a.cpp", b = root / "src/b.cpp"; + fs::path database = root / "compile_commands.json", + selector = root / ".vbs/editor_selection.json"; + SemanticDriver gcc{base / "g++", Workspace::CompilerDriver::gcc}; + SemanticDriver clang{base / "clang++", Workspace::CompilerDriver::clang}; + fs::path marker = base / "executed"; + + Fixture() { + write_file(a, "int a;\n"); + write_file(b, "int b;\n"); + executable(gcc.executable, "first"); + executable(clang.executable, "second"); + } + + void executable(const fs::path &path, std::string_view label) const { + write_file(path, + "#!/bin/sh\n# " + std::string{label} + "\ntouch '" + marker.native() + "'\n"); + fs::permissions(path, fs::perms::owner_all); + } + + vls::WorkspaceLaunch launch(bool authorized = true) const { + Workspace::SettingsOverrides settings; + if (authorized) + settings.tool_approvals = { + {root, Workspace::AuthorityLevel::compiler_use, gcc.executable}, + {root, Workspace::AuthorityLevel::compiler_use, clang.executable}}; + return {.root = root, + .cli_settings = Workspace::settings_from_cli(std::move(settings), base)}; + } + + Json row(const fs::path &file, const SemanticDriver &driver, Strings flags = {}) const { + Json::Array argv{str(driver.executable.native())}; + for (const auto &flag : flags) + argv.push_back(str(flag)); + argv.push_back(str("-c")); + const auto relative = file.lexically_relative(root).native(); + argv.push_back(str(relative)); + return object({{"file", str(relative)}, + {"directory", str(root.native())}, + {"arguments", Json{std::move(argv)}}}); + } + + fs::path native_database() const { + return root / + "out/profiles/debug/editor/generations/0123456789abcdef/compile_commands.json"; + } + + void select_native(int ticket) const { + write_json(selector, object({{"schema_version", Json{std::int64_t{1}}}, + {"ticket", Json{std::int64_t{ticket}}}, + {"selected_profile", str("debug")}, + {"selected_build_root", str((root / "out").native())}, + {"selected_generation_id", str("0123456789abcdef")}, + {"selected_compdb_path", str(native_database().native())}})); + } + + void native_status(std::string_view health) const { + write_json(root / "out/profiles/debug/editor/status.json", + object({{"schema_version", Json{std::int64_t{1}}}, + {"profile", str("debug")}, + {"status", str(health)}, + {"diagnostic", str("")}, + {"generation_id", str("0123456789abcdef")}, + {"compdb_path", str(native_database().native())}, + {"entry_count", Json{std::int64_t{2}}}, + {"readiness_warnings", Json{Json::Array{}}}})); + } +}; +} // namespace + +VOID_TEST(SemanticLease, checked_compdb_command_and_selection_survive_unchanged_status) { + Fixture f; + const auto command = "ccache " + f.gcc.executable.native() + + " -DORDER=1 -freflection -freflection -o unit.o -c src/a.cpp"; + const auto first = object({{"directory", str(f.root.native())}, + {"file", str("src/a.cpp")}, + {"command", str(command)}, + {"output", str("unit.o")}}); + write_json(f.database, Json{Json::Array{first, f.row(f.b, f.gcc)}}); + WorkspaceSession session{f.launch()}; + initialize(session, f.root); + const auto lease = take(acquire(session, f.a, f.gcc)); + const auto &selection = lease.selection(); + require(selection->selected != nullptr); + const auto &context = *selection->selected; + expect(selection->generation->identity().provider == "compdb"); + expect(selection->generation->contexts().size() == 2); + expect(selection->scope->file == f.a && context.key.owning_tu == f.a); + expect(lease.document_uri() == Docs::path_to_file_uri(f.a)); + expect(lease.selection_state().scope() == selection->scope); + expect(context.working_directory == f.root && context.source_language == "c++"); + expect(context.original && context.original->command == command); + expect(context.semantic_arguments == Strings{f.gcc.executable.native(), "-DORDER=1", + "-freflection", "-freflection", "-c", + f.a.native()}); + expect(!context.prerequisites && !context.standard_library); + expect(lease.driver().tool.operation == Workspace::AuthorityLevel::compiler_use); + expect(lease.driver().tool.identity.content_hash_hex.size() == 64); + expect(lease.driver().tool.selection_origin.layer == Workspace::ConfigLayer::cli); + expect(text(status(session, f.root, f.b), "state") == "ready"); + const auto again = take(acquire(session, f.a, f.gcc)); + expect(again.selection() == selection && &again.selection_state() == &lease.selection_state()); + const auto explicit_root = take(acquire(session, f.a, f.gcc, f.root)); + expect(explicit_root.selection() == selection && + &explicit_root.selection_state() == &lease.selection_state()); + expect(again.configuration_generation() == lease.configuration_generation()); + expect(session.validate_semantic_context(lease).has_value()); + expect(!fs::exists(f.marker)); +} + +VOID_TEST(SemanticLease, native_ticket_and_stale_status_fence_the_immutable_row) { + Fixture f; + const auto rows = Json{Json::Array{f.row(f.a, f.gcc, {"-DNATIVE=7"}), f.row(f.b, f.gcc)}}; + write_json(f.native_database(), rows); + f.native_status("valid"); + f.select_native(7); + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc, {"-DFALLBACK"})}}); + WorkspaceSession session{f.launch()}; + initialize(session, f.root); + const auto first = take(acquire(session, f.a, f.gcc)); + expect(first.selection()->generation->contexts().size() == 2); + expect(first.selection()->generation->identity().provider == "vbs"); + expect(first.selection()->selected->original->metadata_file == f.native_database()); + expect(std::ranges::contains(*first.selection()->selected->semantic_arguments, "-DNATIVE=7"sv)); + f.select_native(8); + const auto next = take(acquire(session, f.a, f.gcc)); + expect(first.selection()->generation->identity().revision == + next.selection()->generation->identity().revision); + expect(first.selection() != next.selection()); + fails(session.validate_semantic_context(first), SemanticContextIssue::superseded); + f.native_status("stale"); + expect(text(status(session, f.root, f.a), "state") == "stale"); + fails(acquire(session, f.a, f.gcc), SemanticContextIssue::unavailable); + fails(session.validate_semantic_context(next), SemanticContextIssue::superseded); + f.native_status("valid"); + expect(acquire(session, f.a, f.gcc).has_value()); + expect(!fs::exists(f.marker)); +} + +VOID_TEST(SemanticLease, passive_status_does_not_pin_and_workspace_settings_cannot_grant) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc)}}); + WorkspaceSession session{f.launch()}; + initialize(session, f.root); + expect(text(status(session, f.root, f.a), "state") == "ready"); + const auto replacement = f.base / "new-driver"; + f.executable(replacement, "selected after passive status"); + fs::rename(replacement, f.gcc.executable); + expect(acquire(session, f.a, f.gcc).has_value()); + fails(acquire(session, f.a, f.clang), SemanticContextIssue::wrong_command); + fails(acquire(session, f.a, {f.gcc.executable, Workspace::CompilerDriver::clang}), + SemanticContextIssue::wrong_command); + auto settings = + object({{"toolApprovals", + Json{Json::Array{object({{"root", str(f.root.native())}, + {"operation", str("compilerUse")}, + {"executable", str(f.gcc.executable.native())}})}}}}); + WorkspaceSession unapproved{f.launch(false)}; + initialize(unapproved, f.root, settings); + expect(text(status(unapproved, f.root, f.a), "state") == "ready"); + fails(acquire(unapproved, f.a, f.gcc), SemanticContextIssue::unavailable); + WorkspaceSession passive; + initialize(passive, f.root); + fails(acquire(passive, f.a, f.gcc), SemanticContextIssue::disabled); + const auto other = f.base / "other"; + fs::create_directory(other); + update(session, {folder(other)}, {}); + fails(acquire(session, other / "a.cpp", f.gcc), SemanticContextIssue::disabled); + expect(!fs::exists(f.marker)); +} + +VOID_TEST(SemanticLease, selection_precedes_checked_driver_admission) { + Fixture f; + write_json(f.database, + Json{Json::Array{f.row(f.a, f.clang, {"-DCLANG"}), f.row(f.a, f.gcc, {"-DGCC"})}}); + WorkspaceSession session{f.launch()}; + initialize(session, f.root); + const auto passive_key = text(field(status(session, f.root, f.a), "selected"), "alternative"); + const auto gcc = acquire(session, f.a, f.gcc); + const auto clang = acquire(session, f.a, f.clang); + require(gcc.has_value() != clang.has_value()); + const auto &selected = (gcc ? *gcc : *clang).selection(); + fails(gcc ? clang : gcc, SemanticContextIssue::wrong_command); + expect(selected->alternatives().size() == 2); + expect(selected->selected->key.alternative == passive_key); + expect(std::ranges::contains(*selected->selected->semantic_arguments, + gcc ? "-DGCC"sv : "-DCLANG"sv)); +} + +VOID_TEST(SemanticLease, identical_database_replacement_requires_a_new_capture) { + Fixture f; + const auto rows = Json{Json::Array{f.row(f.a, f.gcc)}}; + write_json(f.database, rows); + WorkspaceSession session{f.launch()}; + initialize(session, f.root); + const auto original = take(acquire(session, f.a, f.gcc)); + const auto old_file = f.root / "first.json"; + fs::rename(f.database, old_file); + write_json(f.database, rows); + const auto replacement = take(acquire(session, f.a, f.gcc)); + expect(replacement.selection() != original.selection()); + expect(replacement.selection()->generation->identity().revision == + original.selection()->generation->identity().revision); + expect(session.validate_semantic_context(replacement).has_value()); + fails(session.validate_semantic_context(original), SemanticContextIssue::superseded); + fs::rename(old_file, f.database); + fails(session.validate_semantic_context(replacement), SemanticContextIssue::superseded); + fails(session.validate_semantic_context(original), SemanticContextIssue::superseded); + expect(acquire(session, f.a, f.gcc).has_value()); +} + +VOID_TEST(SemanticLease, observed_native_precedence_cannot_restore_an_old_fallback_lease) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc)}}); + WorkspaceSession session{f.launch()}; + initialize(session, f.root); + const auto original = take(acquire(session, f.a, f.gcc)); + write_file(f.selector, "{"); + const auto invalid = status(session, f.root, f.a); + expect(text(invalid, "provider") == "vbs" && text(invalid, "state") == "degraded"); + fs::remove(f.selector); + // The original database, TU, driver and selector absence all match again. + fails(session.validate_semantic_context(original), SemanticContextIssue::superseded); + const auto fresh = take(acquire(session, f.a, f.gcc)); + expect(fresh.selection() != original.selection()); + expect(session.validate_semantic_context(fresh).has_value()); +} + +VOID_TEST(SemanticLease, failed_final_status_check_permanently_expires_a_fallback_lease) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc)}}); + Gate gate; + WorkspaceSession session{f.launch(), [&] { gate.hook(); }}; + initialize(session, f.root); + const auto fallback = take(acquire(session, f.a, f.gcc)); + const auto discarded = gate.during([&] { return status(session, f.root, f.b); }, + [&] { write_file(f.selector, "{"); }); + expect(text(discarded, "state") == "stale"); + fs::remove(f.selector); + fails(session.validate_semantic_context(fallback), SemanticContextIssue::superseded); + expect(acquire(session, f.a, f.gcc).has_value()); +} + +VOID_TEST(SemanticLease, disproved_selector_absence_retires_both_checked_driver_imports) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc), f.row(f.b, f.clang)}}); + WorkspaceSession session{f.launch()}; + initialize(session, f.root); + const auto a = take(acquire(session, f.a, f.gcc)); + const auto b = take(acquire(session, f.b, f.clang)); + write_file(f.selector, "{"); + fails(session.validate_semantic_context(a), SemanticContextIssue::superseded); + fs::remove(f.selector); + fails(session.validate_semantic_context(b), SemanticContextIssue::superseded); + expect(acquire(session, f.b, f.clang).has_value()); +} + +VOID_TEST(SemanticLease, changed_pin_revokes_old_work_and_preserves_the_other_approved_driver) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc), f.row(f.b, f.clang)}}); + WorkspaceSession session{f.launch()}; + initialize(session, f.root); + const auto a = take(acquire(session, f.a, f.gcc)); + const auto b = take(acquire(session, f.b, f.clang)); + expect(a.driver().tool.trust_generation == b.driver().tool.trust_generation); + auto former = f.base / "former-driver"; + fs::rename(f.gcc.executable, former); + f.executable(f.gcc.executable, "replacement"); + fails(session.validate_semantic_context(a), SemanticContextIssue::superseded); + fails(session.validate_semantic_context(b), SemanticContextIssue::superseded); + const auto recovered = take(acquire(session, f.b, f.clang)); + expect(recovered.driver().tool.trust_generation > b.driver().tool.trust_generation); + expect(recovered.configuration_generation() == b.configuration_generation()); + expect(text(status(session, f.root, f.b), "state") == "ready"); + fs::rename(former, f.gcc.executable); + fails(acquire(session, f.a, f.gcc), SemanticContextIssue::unavailable); + expect(session.validate_semantic_context(recovered).has_value()); + expect(!fs::exists(f.marker)); +} + +VOID_TEST(SemanticLease, nested_folder_fences_implicit_acquisition_and_validation_only) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc)}}); + Gate gate; + WorkspaceSession session{f.launch(), [&] { gate.hook(); }}; + initialize(session, f.root); + const auto explicit_outer = take(acquire(session, f.a, f.gcc, f.root)); + const auto inner = folder(f.a.parent_path()); + auto late = gate.during([&] { return acquire(session, f.a, f.gcc); }, + [&] { update(session, {inner}, {}); }); + fails(late, SemanticContextIssue::superseded); + fails(acquire(session, f.a, f.gcc), SemanticContextIssue::unavailable); + expect(session.validate_semantic_context(explicit_outer).has_value()); + update(session, {}, {inner}); + const auto implicit = take(acquire(session, f.a, f.gcc)); + auto stale = gate.during([&] { return session.validate_semantic_context(implicit); }, + [&] { + update(session, {inner}, {}); + update(session, {}, {inner}); + }); + fails(stale, SemanticContextIssue::superseded); + expect(session.validate_semantic_context(explicit_outer).has_value()); + fails(session.validate_semantic_context(implicit), SemanticContextIssue::superseded); + expect(acquire(session, f.a, f.gcc).has_value()); +} + +VOID_TEST(SemanticLease, independent_cold_document_observations_and_status_can_complete) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc), f.row(f.b, f.gcc)}}); + Gate gate; + WorkspaceSession session{f.launch(), [&] { gate.hook(); }}; + initialize(session, f.root); + std::optional b; + const auto a = + take(gate.during([&] { return acquire(session, f.a, f.gcc); }, + [&] { + b = take(acquire(session, f.b, f.gcc)); + expect(text(status(session, f.root, f.b), "state") == "ready"); + })); + require(b.has_value()); + expect(a.selection()->selected->key.owning_tu == f.a); + expect(b->selection()->selected->key.owning_tu == f.b); + expect(session.validate_semantic_context(a).has_value()); + expect(session.validate_semantic_context(*b).has_value()); + expect(take(acquire(session, f.a, f.gcc)).selection() == a.selection()); +} + +VOID_TEST(SemanticLease, newest_document_request_fences_older_success_and_failure) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc)}}); + Gate gate; + WorkspaceSession session{f.launch(), [&] { gate.hook(); }}; + initialize(session, f.root); + std::optional accepted; + const auto late_failure = gate.during([&] { return acquire(session, f.a, f.clang); }, + [&] { accepted = take(acquire(session, f.a, f.gcc)); }); + fails(late_failure, SemanticContextIssue::superseded); + require(accepted.has_value()); + expect(session.validate_semantic_context(*accepted).has_value()); + const auto late_success = gate.during( + [&] { return acquire(session, f.a, f.gcc); }, + [&] { fails(acquire(session, f.a, f.clang), SemanticContextIssue::wrong_command); }); + fails(late_success, SemanticContextIssue::superseded); + fails(session.validate_semantic_context(*accepted), SemanticContextIssue::superseded); +} + +VOID_TEST(SemanticLease, explicit_revocation_between_observation_and_installation) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc), f.row(f.b, f.gcc)}}); + Gate gate; + WorkspaceSession session{f.launch(), [&] { gate.hook(); }}; + initialize(session, f.root); + const auto accepted = take(acquire(session, f.a, f.gcc)); + const auto late = gate.during([&] { return acquire(session, f.b, f.gcc); }, + [&] { session.revoke_root_authority(f.root); }); + fails(late, SemanticContextIssue::superseded); + fails(session.validate_semantic_context(accepted), SemanticContextIssue::superseded); + fails(acquire(session, f.b, f.gcc), SemanticContextIssue::unavailable); + expect(text(status(session, f.root, f.a), "state") == "ready"); +} + +VOID_TEST(SemanticLease, superseded_native_failure_cannot_retire_a_newer_fallback_selection) { + Fixture f; + const auto rows = Json{Json::Array{f.row(f.a, f.gcc), f.row(f.b, f.clang)}}; + write_json(f.database, rows); + write_json(f.native_database(), rows); + f.native_status("valid"); + Gate gate; + WorkspaceSession session{f.launch(), [&] { gate.hook(); }}; + initialize(session, f.root); + auto latest = take(acquire(session, f.a, f.gcc)); + f.select_native(9); + auto stale = gate.during([&] { return acquire(session, f.a, f.clang); }, + [&] { + fs::remove(f.selector); + latest = take(acquire(session, f.a, f.gcc)); + }); + fails(stale, SemanticContextIssue::superseded); + expect(session.validate_semantic_context(latest).has_value()); +} + +VOID_TEST(SemanticLease, negative_response_lookup_and_editor_alias_retarget_expire_leases) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc), f.row(f.b, f.gcc, {"@later.rsp"})}}); + const auto alias = f.root / "alias.cpp"; + fs::create_symlink("src/a.cpp", alias); + WorkspaceSession session{f.launch()}; + initialize(session, f.root); + const auto a = take(acquire(session, alias, f.gcc)); + expect(a.selection()->scope->file == f.a); + fails(acquire(session, f.b, f.gcc), SemanticContextIssue::wrong_command); + write_file(f.root / "later.rsp", "-DRESPONSE"); + fails(session.validate_semantic_context(a), SemanticContextIssue::superseded); + const auto b = take(acquire(session, f.b, f.gcc)); + expect(std::ranges::contains(*b.selection()->selected->semantic_arguments, "-DRESPONSE"sv)); + const auto alias_a = take(acquire(session, alias, f.gcc)); + const auto saved = f.root / "alias-saved.cpp"; + fs::rename(alias, saved); + fs::create_symlink("src/b.cpp", alias); + fails(session.validate_semantic_context(alias_a), SemanticContextIssue::superseded); + const auto alias_b = take(acquire(session, alias, f.gcc)); + expect(alias_b.selection()->scope->file == f.b && + session.validate_semantic_context(b).has_value()); + fs::rename(saved, alias); + fails(session.validate_semantic_context(alias_b), SemanticContextIssue::superseded); + fails(session.validate_semantic_context(alias_a), SemanticContextIssue::superseded); +} + +VOID_TEST(SemanticLease, settings_and_root_incarnation_are_stable_only_for_their_lifetimes) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc)}}); + Gate gate; + WorkspaceSession session{f.launch(), [&] { gate.hook(); }}; + initialize(session, f.root); + const auto first = take(acquire(session, f.a, f.gcc)); + auto config = + object({{"settings", + object({{"voidLanguageServer", object({{"selectedProfile", str("debug")}})}})}}); + const auto late = gate.during([&] { return acquire(session, f.a, f.gcc); }, + [&] { require(session.configure(&config).has_value()); }); + fails(late, SemanticContextIssue::superseded); + fails(session.validate_semantic_context(first), SemanticContextIssue::superseded); + const auto second = take(acquire(session, f.a, f.gcc)); + expect(second.configuration_generation() > first.configuration_generation()); + require(session.configure(&config).has_value()); + expect(take(acquire(session, f.a, f.gcc)).selection() == second.selection()); + const auto old_incarnation = second.selection()->scope->workspace.session; + const auto removed = gate.during([&] { return session.validate_semantic_context(second); }, + [&] { update(session, {folder(f.root)}, {folder(f.root)}); }); + fails(removed, SemanticContextIssue::superseded); + expect(text(status(session, f.root, f.a), "incarnation") != old_incarnation); + fails(acquire(session, f.a, f.gcc), SemanticContextIssue::unavailable); +} + +VOID_TEST(SemanticLease, cache_eviction_and_session_shutdown_leave_immutable_inputs_readable) { + Fixture f; + write_json(f.database, Json{Json::Array{f.row(f.a, f.gcc)}}); + std::optional retained; + { + WorkspaceSession session{f.launch()}; + initialize(session, f.root); + retained = take(acquire(session, f.a, f.gcc)); + for (int i = 0; i < 32; ++i) + fails(acquire(session, f.root / ("new-" + std::to_string(i) + ".cpp"), f.gcc), + SemanticContextIssue::no_command); + fails(session.validate_semantic_context(*retained), SemanticContextIssue::superseded); + retained = take(acquire(session, f.a, f.gcc)); + WorkspaceSession other{f.launch()}; + initialize(other, f.root); + fails(other.validate_semantic_context(*retained), SemanticContextIssue::superseded); + expect(session.validate_semantic_context(*retained).has_value()); + } + require(retained.has_value()); + expect(retained->selection()->selected->original->arguments->front() == + f.gcc.executable.native()); + expect(retained->selection_state().scope()->file == f.a); + expect(!fs::exists(f.marker)); +} diff --git a/tests/workspace/WorkspaceTests.cpp b/tests/workspace/WorkspaceTests.cpp new file mode 100644 index 0000000..94b3607 --- /dev/null +++ b/tests/workspace/WorkspaceTests.cpp @@ -0,0 +1,611 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace Void::LanguageServer::Workspace; +using Void::Testing::expect; +using Void::Testing::require; +using enum AuthorityLevel; +namespace fs = std::filesystem; +namespace Protocol = Void::LanguageServer::Protocol; + +void write(const fs::path &path, std::string_view bytes) { + std::ofstream output(path, std::ios::binary); + output.write(bytes.data(), static_cast(bytes.size())); + output.close(); + require(output.good()); +} + +void make_tool(const fs::path &path, std::string_view bytes = "abc") { + write(path, bytes); + fs::permissions(path, fs::perms::owner_read | fs::perms::owner_write | fs::perms::owner_exec); +} + +PartialWorkspaceSettings workspace(const fs::path &root, std::string_view json = "{}") { + auto payload = Protocol::parse_json(json); + require(payload.has_value()); + return parse_workspace_settings(*payload, root); +} + +MergedConfiguration selected(const fs::path &root, std::vector selections) { + SettingsOverrides flags; + flags.tool_approvals = std::move(selections); + auto cli = settings_from_cli(std::move(flags), root); + return merge_configuration(workspace(root), nullptr, &cli); +} + +bool diagnosed(const MergedConfiguration &merged, std::string_view key, ConfigIssue code) { + return std::ranges::any_of(merged.diagnostics(), + [&](const auto &d) { return d.key == key && d.issue == code; }); +} + +template bool refused(const std::expected &value, TrustError error) { + return !value && value.error() == error; +} + +struct Fixture { + Void::FileSystem::TempDir temp{"vls_workspace_"}; + fs::path root = temp.path() / "one", other = temp.path() / "one-more"; + fs::path tool = temp.path() / "g++"; + Fixture() { + fs::create_directories(root / "out"); + fs::create_directories(other); + make_tool(tool); + } + std::uint64_t install(TrustPolicy &policy, AuthorityLevel purpose) const { + auto version = policy.replace_configuration(selected(root, {{root, purpose, tool}})); + require(version.has_value()); + auto pin = policy.pin_approved_tool(root, purpose, tool); + require(pin.has_value()); + return *version; + } + BuildInvocation action(std::uint64_t gen) const { + return {root, + tool, + root / "out", + {"build", "demo"}, + "provider:1/inputs:a", + "environment:default", + gen}; + } +}; +} // namespace + +VOID_TEST(WorkspaceTests, precedence_origins_and_owning_bases) { + Fixture f; + write(f.temp.path() / "user.json", R"({"voidLanguageServer":{ + "provider":"compdb","compdbPath":"user-db","enableBackgroundIndexing":false, + "toolApprovals":[{"root":"one","operation":"compilerUse","executable":"g++"}, + {"root":"one-more","operation":"metadataRefresh","executable":"g++"}]}})"); + auto user = read_user_settings(f.temp.path() / "user.json"); + require(user.has_value()); + expect(user->origin().layer == ConfigLayer::user_runtime && + user->origin().selected_file == f.temp.path() / "user.json"); + auto local = workspace( + f.root, + R"({"provider":"vbs","vbsManifestPath":"local/export.json","compdbPath":"local-db"})"); + SettingsOverrides flags; + flags.provider = ProviderPreference::none; + flags.selected_profile = "release"; + flags.vbs_manifest_path = "cli/export.json"; + auto cli = settings_from_cli(flags, f.other); + auto lower = merge_configuration(local, &*user); + expect(lower.effective().provider == ProviderPreference::compdb); + expect(lower.effective().vbs_manifest_path == f.root / "local/export.json"); + auto merged = merge_configuration(local, &*user, &cli); + const auto &s = merged.effective(); + expect(s.provider == ProviderPreference::none && !s.enable_background_indexing); + expect(s.compdb_path == f.temp.path() / "user-db" && + s.vbs_manifest_path == f.other / "cli/export.json"); + expect(s.compdb_origin.layer == ConfigLayer::user_runtime && + s.compdb_origin.selected_file == f.temp.path() / "user.json"); + expect(s.vbs_manifest_origin.layer == ConfigLayer::cli && + s.vbs_manifest_origin.base == f.other); + expect(merge_configuration(local).effective().compdb_origin.layer == + ConfigLayer::workspace_local); + expect(s.selected_profile == "release"); + expect(s.tool_approvals_origin.layer == ConfigLayer::user_runtime); + expect(s.tool_approvals_origin.selected_file == f.temp.path() / "user.json"); + require(s.tool_approvals.size() == 1); + expect(s.tool_approvals[0] == ToolSelection{f.root, compiler_use, f.tool}); + TrustPolicy policy; + require(policy.replace_configuration(merged).has_value()); + const auto observed = policy.pin_approved_tool(f.root, compiler_use, f.tool); + require(observed.has_value()); + expect(observed->selection_origin.selected_file == s.tool_approvals_origin.selected_file); + auto second = merge_configuration(workspace(f.other), &*user); + require(second.effective().tool_approvals.size() == 1); + expect(second.effective().tool_approvals[0] == + ToolSelection{f.other, trusted_metadata_refresh, f.tool}); +} + +VOID_TEST(WorkspaceTests, workspace_cannot_relabel_or_grant_authority) { + Fixture f; + auto local = workspace( + f.root, R"({"trustedRoots":["."],"approvedCompilers":["g++"],"approvedWrappers":["custom"], + "allowMetadataRefresh":true,"allowExplicitBuildActions":true,"allowCompilerPlugins":true, + "toolApprovals":[{"root":".","operation":"compilerUse","executable":"g++"}]})"); + auto merged = merge_configuration(local, &local, &local); + for (auto key : + {"trustedRoots", "approvedCompilers", "approvedWrappers", "allowMetadataRefresh", + "allowExplicitBuildActions", "allowCompilerPlugins", "toolApprovals"}) + expect(diagnosed(merged, key, ConfigIssue::untrusted_setting)); + expect(diagnosed(merged, "", ConfigIssue::invalid_origin)); + expect(merged.effective().tool_approvals.empty()); + expect(!merged.effective().allow_metadata_refresh && + !merged.effective().allow_explicit_build_actions); + TrustPolicy policy; + require(policy.replace_configuration(merged).has_value()); + expect(refused(policy.pin_approved_tool(f.root, compiler_use, f.tool), + TrustError::untrusted_root)); + write(f.temp.path() / "legacy.json", + R"({"trustedRoots":["one"],"approvedCompilers":["g++"],"allowMetadataRefresh":true})"); + auto legacy = read_user_settings(f.temp.path() / "legacy.json"); + require(legacy.has_value()); + require(policy.replace_configuration(merge_configuration(local, &*legacy)).has_value()); + expect(refused(policy.pin_approved_tool(f.root, trusted_metadata_refresh, f.tool), + TrustError::untrusted_root)); +} + +VOID_TEST(WorkspaceTests, malformed_fields_and_resource_ceilings) { + Fixture f; + const auto bad = + merge_configuration(workspace(f.root, R"({"provider":false,"vbsManifestPath":"", + "compdbPath":2,"enableBackgroundIndexing":"yes","selectedProfile":null,"workerMemoryLimitMib":0, + "maxSemanticWorkers":2.0,"maxResponseFileDepth":-1,"maxCompdbBytes":2147483649, + "maxManifestBytes":"100","maxResponseFileBytes":null,"unknownSetting":1})")); + for (auto key : + {"provider", "vbsManifestPath", "compdbPath", "enableBackgroundIndexing", + "selectedProfile", "workerMemoryLimitMib", "maxSemanticWorkers", "maxResponseFileDepth", + "maxCompdbBytes", "maxManifestBytes", "maxResponseFileBytes"}) + expect(diagnosed(bad, key, ConfigIssue::invalid_value)); + expect(diagnosed(bad, "unknownSetting", ConfigIssue::unsupported)); + const auto local = workspace(f.root, R"({"maxSemanticWorkers":64,"workerMemoryLimitMib":65536, + "maxResponseFileDepth":32,"maxResponseFileBytes":16777216,"maxCompdbBytes":1073741824,"maxManifestBytes":1024})"); + auto merged = merge_configuration(local); + for (auto key : {"maxSemanticWorkers", "workerMemoryLimitMib", "maxResponseFileDepth", + "maxResponseFileBytes", "maxCompdbBytes"}) + expect(diagnosed(merged, key, ConfigIssue::resource_limit)); + expect(merged.effective().limits.max_semantic_workers == + ResourceLimitsConfig{}.max_semantic_workers); + expect(merged.effective().limits.max_manifest_bytes == 1024); + SettingsOverrides flags; + flags.max_semantic_workers = 8; + flags.worker_memory_limit_mib = 512; + flags.allow_compiler_plugins = true; + auto cli = settings_from_cli(flags, f.root); + auto runtime = merge_configuration(local, nullptr, &cli); + expect(runtime.effective().limits.max_semantic_workers == 8 && + runtime.effective().limits.worker_memory_limit_mib == 512); + expect(!runtime.effective().allow_compiler_plugins && + diagnosed(runtime, "allowCompilerPlugins", ConfigIssue::unsupported)); + auto nested = + merge_configuration(workspace(f.root, R"({"voidLanguageServer":false,"provider":"none"})")); + expect(diagnosed(nested, "", ConfigIssue::invalid_value) && + nested.effective().provider == ProviderPreference::auto_detect); + expect(diagnosed(merge_configuration(workspace("relative")), "", ConfigIssue::invalid_origin)); +} + +VOID_TEST(WorkspaceTests, trusted_replacements_are_all_or_nothing) { + Fixture f; + const auto file = f.temp.path() / "settings"; + write(file, + R"({"toolApprovals":[{"root":"one","operation":"metadataRefresh","executable":"g++"}]})"); + auto user = read_user_settings(file); + require(user.has_value()); + const auto local = workspace(f.root); + SettingsOverrides flags; + flags.tool_approvals = std::vector{ + {f.root, compiler_use, f.tool}, {f.temp.path() / "missing", compiler_use, f.tool}}; + auto invalid = settings_from_cli(flags, f.root); + auto rejected = merge_configuration(local, &*user, &invalid); + expect(diagnosed(rejected, "toolApprovals", ConfigIssue::invalid_value)); + expect(rejected.effective().tool_approvals.empty()); + flags = {}; + flags.allow_metadata_refresh = false; + auto veto = settings_from_cli(flags, f.root); + expect(merge_configuration(local, &*user, &veto).effective().tool_approvals.empty()); + write( + file, + R"({"allowExplicitBuildActions":"yes","approvedWrappers":["unknown"],"allowCompilerPlugins":5, + "toolApprovals":[{"root":"one","operation":"compilerUse","executable":"g++"},{"operation":"shell"}]})"); + user = read_user_settings(file); + require(user.has_value()); + rejected = merge_configuration(local, &*user); + for (auto key : + {"allowExplicitBuildActions", "approvedWrappers", "allowCompilerPlugins", "toolApprovals"}) + expect(diagnosed(rejected, key, ConfigIssue::invalid_value)); + expect(rejected.effective().tool_approvals.empty() && + rejected.effective().approved_wrappers.empty()); +} + +VOID_TEST(WorkspaceTests, explicit_user_file_and_executable_read_bounds) { + Fixture f; + expect(!read_user_settings("relative/settings")); + expect(!read_user_settings(f.root)); + expect(refused(inspect_tool_identity(f.root), TrustError::not_regular)); + expect(refused(inspect_tool_identity("g++"), TrustError::invalid_path)); + expect(refused(inspect_tool_identity(f.root / "missing"), TrustError::unavailable_file)); + const auto fifo = f.root / "pipe"; + require(::mkfifo(fifo.c_str(), 0700) == 0); + expect(refused(inspect_tool_identity(fifo), TrustError::not_regular)); + expect(!read_user_settings(fifo)); + write(f.root / "settings", "{"); + expect(!read_user_settings(f.root / "settings")); + fs::resize_file(f.root / "settings", 1024 * 1024 + 1); + expect(!read_user_settings(f.root / "settings")); + fs::resize_file(f.tool, max_tool_bytes + 1); + expect(refused(inspect_tool_identity(f.tool), TrustError::too_large)); +} + +VOID_TEST(WorkspaceTests, hash_revalidated_with_identical_length_and_mtime) { + Fixture f; + TrustPolicy policy; + const auto generation = f.install(policy, compiler_use); + const auto pinned = policy.check_tool(f.root, compiler_use, f.tool, generation); + require(pinned.has_value()); + expect(pinned->identity.content_hash_hex == + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + auto incomplete = pinned->identity; + incomplete.content_hash_hex.clear(); + expect(refused(revalidate_tool_identity(incomplete), TrustError::digest_unavailable)); + const auto mtime = fs::last_write_time(f.tool); + write(f.tool, "abd"); + fs::last_write_time(f.tool, mtime); + expect(refused(policy.check_tool(f.root, compiler_use, f.tool, generation), + TrustError::identity_changed)); + expect(policy.generation(f.root) != generation); + write(f.tool, "abc"); + expect(!policy.pin_approved_tool(f.root, compiler_use, f.tool)); + expect(f.install(policy, compiler_use) > generation); +} + +VOID_TEST(WorkspaceTests, selected_symlink_permission_and_replacement_identity) { + Fixture f; + auto first = f.tool; + auto second = f.temp.path() / "same-bytes"; + fs::create_hard_link(first, second); + f.tool = f.root / "compiler"; + fs::create_symlink(first, f.tool); + TrustPolicy policy; + auto gen = f.install(policy, compiler_use); + auto pin = policy.check_tool(f.root, compiler_use, f.tool, gen); + require(pin.has_value()); + expect(pin->identity.selected_path == f.tool && pin->identity.canonical_path == first); + fs::remove(f.tool); + fs::create_symlink(second, f.tool); + expect(refused(policy.check_tool(f.root, compiler_use, f.tool, gen), + TrustError::identity_changed)); + gen = f.install(policy, compiler_use); + fs::permissions(second, fs::perms::group_exec, fs::perm_options::add); + expect(refused(policy.check_tool(f.root, compiler_use, f.tool, gen), + TrustError::identity_changed)); + gen = f.install(policy, compiler_use); + fs::permissions(second, fs::perms::owner_read); + expect( + refused(policy.check_tool(f.root, compiler_use, f.tool, gen), TrustError::not_executable)); + fs::permissions(second, fs::perms::owner_read | fs::perms::owner_write | fs::perms::owner_exec); + gen = f.install(policy, compiler_use); + make_tool(f.root / "replacement"); + fs::rename(f.root / "replacement", second); + expect(refused(policy.check_tool(f.root, compiler_use, f.tool, gen), + TrustError::identity_changed)); +} + +VOID_TEST(WorkspaceTests, exact_roots_and_operation_specific_pins) { + Fixture f; + const auto nested = f.root / "out"; + const auto alternate = f.other / "g++"; + make_tool(alternate); + const std::vector selections{{f.root, compiler_use, f.tool}, + {f.root, trusted_metadata_refresh, alternate}, + {f.other, trusted_metadata_refresh, f.tool}}; + TrustPolicy policy; + auto a = policy.replace_configuration(selected(f.root, selections)); + auto b = policy.replace_configuration(selected(f.other, selections)); + require(a.has_value() && b.has_value()); + expect( + refused(policy.check_tool(f.root, compiler_use, f.tool, *a), TrustError::tool_not_pinned)); + require(policy.pin_approved_tool(f.root, compiler_use, f.tool).has_value()); + const auto alternate_spelling = + f.tool.parent_path().native() + "//" + f.tool.filename().native(); + expect(refused(policy.check_tool(f.root, compiler_use, alternate_spelling, *a), + TrustError::tool_not_approved)); + require(policy.pin_approved_tool(f.other, trusted_metadata_refresh, f.tool).has_value()); + expect(refused(policy.pin_approved_tool(f.other, compiler_use, f.tool), + TrustError::operation_not_approved)); + expect(refused(policy.pin_approved_tool(f.root, trusted_metadata_refresh, f.tool), + TrustError::tool_not_approved)); + expect(refused(policy.pin_approved_tool(nested, compiler_use, f.tool), + TrustError::untrusted_root)); + expect(refused(policy.pin_approved_tool(f.root, passive_read, f.tool), + TrustError::operation_not_approved)); + expect(refused(policy.check_tool(f.root, explicit_build_action, f.tool, *a), + TrustError::explicit_action_required)); + policy.revoke_root_authority(f.root); + expect(policy.generation(f.other) == *b && + policy.check_tool(f.other, trusted_metadata_refresh, f.tool, *b).has_value()); + require(policy.replace_configuration(selected(f.root, selections)).has_value()); + require(policy.pin_approved_tool(f.root, compiler_use, f.tool).has_value()); + expect( + refused(policy.check_tool(f.root, compiler_use, f.tool, *a), TrustError::stale_generation)); +} + +VOID_TEST(WorkspaceTests, relative_tool_selection_keeps_symlink_traversal) { + Fixture f; + fs::create_directory(f.other / "deep"); + fs::create_directory_symlink(f.other / "deep", f.temp.path() / "links"); + make_tool(f.other / "g++", "selected"); + make_tool(f.root / "g++", "selected"); + write( + f.temp.path() / "user", + R"({"toolApprovals":[{"root":"one","operation":"compilerUse","executable":"links/../g++"}]})"); + auto user = read_user_settings(f.temp.path() / "user"); + require(user.has_value()); + TrustPolicy policy; + auto gen = policy.replace_configuration(merge_configuration(workspace(f.root), &*user)); + require(gen.has_value()); + const auto spelling = f.temp.path() / "links/../g++"; + auto pin = policy.pin_approved_tool(f.root, compiler_use, spelling); + require(pin.has_value()); + expect(pin->identity.selected_path.native() == spelling.native() && + pin->identity.canonical_path == f.other / "g++"); + fs::remove(f.temp.path() / "links"); + fs::create_directory_symlink(f.root / "out", f.temp.path() / "links"); + expect(refused(policy.check_tool(f.root, compiler_use, spelling, *gen), + TrustError::identity_changed)); +} + +VOID_TEST(WorkspaceTests, replacing_workspace_directory_revokes_its_pins) { + Fixture f; + TrustPolicy policy; + const auto gen = f.install(policy, compiler_use); + fs::rename(f.root, f.temp.path() / "previous"); + fs::create_directory(f.root); + expect( + refused(policy.check_tool(f.root, compiler_use, f.tool, gen), TrustError::untrusted_root)); + expect(policy.generation(f.root) > gen); + expect(!policy.pin_approved_tool(f.root, compiler_use, f.tool)); +} + +VOID_TEST(WorkspaceTests, cached_settings_cannot_rearm_revoked_pins) { + Fixture f; + const auto file = f.temp.path() / "selected.json"; + write(file, + R"({"toolApprovals":[{"root":"one","operation":"compilerUse","executable":"g++"}]})"); + auto user = read_user_settings(file); + require(user.has_value()); + auto merged = merge_configuration(workspace(f.root), &*user); + TrustPolicy policy; + auto gen = policy.replace_configuration(merged); + require(gen.has_value() && policy.pin_approved_tool(f.root, compiler_use, f.tool).has_value()); + auto changed_workspace = + merge_configuration(workspace(f.root, R"({"provider":"compdb"})"), &*user); + expect(policy.replace_configuration(changed_workspace) == gen); + require(policy.check_tool(f.root, compiler_use, f.tool, *gen).has_value()); + // This trusted input was read before revocation, even though delivery to the policy is later. + auto delayed = read_user_settings(file); + require(delayed.has_value()); + write(f.tool, "abd"); + require(refused(policy.check_tool(f.root, compiler_use, f.tool, *gen), + TrustError::identity_changed)); + expect(refused(policy.replace_configuration(changed_workspace), TrustError::stale_generation)); + expect(refused(policy.replace_configuration(merge_configuration(workspace(f.root), &*delayed)), + TrustError::stale_generation)); + expect(!policy.pin_approved_tool(f.root, compiler_use, f.tool)); + auto fresh = read_user_settings(file); + require(fresh.has_value()); + gen = policy.replace_configuration(merge_configuration(workspace(f.root), &*fresh)); + require(gen.has_value() && policy.pin_approved_tool(f.root, compiler_use, f.tool).has_value()); + policy.revoke_root_authority(f.root); + expect(refused(policy.replace_configuration(merge_configuration(workspace(f.root), &*fresh)), + TrustError::stale_generation)); +} + +VOID_TEST(WorkspaceTests, revocation_during_revalidation_commits_before_callback) { + Fixture f; + fs::resize_file(f.tool, 8 * 1024 * 1024); + std::uint64_t seen = 0; + TrustPolicy policy([&](const fs::path &root, std::uint64_t gen) noexcept { + if (policy.generation(root) == gen) { + seen = gen; // callback reenters the policy + policy.revoke_root_authority(root); + } + }); + const auto gen = f.install(policy, compiler_use); + Void::System::OwnedFd watch{::inotify_init1(IN_NONBLOCK | IN_CLOEXEC)}; + require(watch.valid() && ::inotify_add_watch(watch.get(), f.tool.c_str(), IN_ACCESS) >= 0); + auto work = std::async(std::launch::async, + [&] { return policy.check_tool(f.root, compiler_use, f.tool, gen); }); + pollfd event{watch.get(), POLLIN, 0}; + require(::poll(&event, 1, 5000) == 1); + policy.revoke_root_authority(f.root); + const auto result = work.get(); + expect(seen > gen && seen == policy.generation(f.root)); + // If the reader won scheduling, its completed report still carries the superseded generation. + expect(result ? result->trust_generation != seen + : result.error() == TrustError::stale_generation); + expect(!policy.check_tool(f.root, compiler_use, f.tool, gen)); +} + +VOID_TEST(WorkspaceTests, build_approval_binds_every_invocation_field) { + Fixture f; + TrustPolicy policy; + auto request = f.action(f.install(policy, explicit_build_action)); + auto ticket = policy.approve_build_action(request); + require(ticket.has_value()); + expect(refused(policy.approve_build_action(request), TrustError::action_pending)); + auto mismatch = [&](auto edit) { + auto different = request; + edit(different); + expect(refused(policy.consume_build_action(*ticket, different), + TrustError::invocation_mismatch)); + }; + mismatch([&](auto &v) { v.root = f.other; }); + mismatch([&](auto &v) { v.working_directory = f.root; }); + mismatch([&](auto &v) { v.executable = f.root / "other-tool"; }); + mismatch([&](auto &v) { + v.executable = f.tool.parent_path().native() + "//" + f.tool.filename().native(); + }); + mismatch([](auto &v) { std::ranges::reverse(v.arguments); }); + mismatch([](auto &v) { v.input_identity += "2"; }); + mismatch([](auto &v) { v.environment_identity += "2"; }); + mismatch([](auto &v) { ++v.trust_generation; }); + TrustPolicy other; + (void)f.install(other, explicit_build_action); + require(other.approve_build_action(request).has_value()); + expect(refused(other.consume_build_action(*ticket, request), TrustError::action_not_current)); + require(policy.consume_build_action(*ticket, request).has_value()); + expect(refused(policy.consume_build_action(*ticket, request), TrustError::action_not_current)); + ticket = policy.approve_build_action(request); + require(ticket.has_value()); + expect(policy.cancel_build_action(*ticket) && !policy.cancel_build_action(*ticket)); + expect(!policy.consume_build_action(*ticket, request)); +} + +VOID_TEST(WorkspaceTests, build_scope_changes_and_revocation_invalidate_pending_action) { + Fixture f; + TrustPolicy policy; + auto action = f.action(f.install(policy, explicit_build_action)); + auto invalid = action; + invalid.working_directory = f.other; + expect(refused(policy.approve_build_action(invalid), TrustError::invalid_invocation)); + fs::create_directory_symlink(f.other, f.root / "alias"); + invalid.working_directory = f.root / "alias"; + expect(refused(policy.approve_build_action(invalid), TrustError::invalid_invocation)); + invalid = action; + invalid.arguments.emplace_back("test\0tail", 9); + expect(refused(policy.approve_build_action(invalid), TrustError::invalid_invocation)); + invalid = action; + invalid.input_identity.clear(); + expect(refused(policy.approve_build_action(invalid), TrustError::invalid_invocation)); + auto ticket = policy.approve_build_action(action); + require(ticket.has_value()); + fs::rename(action.working_directory, f.root / "retired"); + fs::create_directory(action.working_directory); + expect(refused(policy.consume_build_action(*ticket, action), TrustError::invalid_invocation)); + ticket = policy.approve_build_action(action); + require(ticket.has_value()); + policy.revoke_root_authority(f.root); + expect(!policy.consume_build_action(*ticket, action)); + action.trust_generation = f.install(policy, explicit_build_action); + ticket = policy.approve_build_action(action); + require(ticket.has_value()); + write(f.tool, "new"); + expect(refused(policy.consume_build_action(*ticket, action), TrustError::identity_changed)); + expect(!policy.consume_build_action(*ticket, action)); +} + +VOID_TEST(WorkspaceTests, concurrent_build_ticket_has_one_consumer) { + Fixture f; + TrustPolicy policy; + auto request = f.action(f.install(policy, explicit_build_action)); + auto ticket = policy.approve_build_action(request); + require(ticket.has_value()); + std::barrier start(2); + auto consume = [&] { + start.arrive_and_wait(); + return policy.consume_build_action(*ticket, request).has_value(); + }; + auto other = std::async(std::launch::async, consume); + const bool first = consume(); + expect(first != other.get()); +} + +VOID_TEST(WorkspaceTests, supported_compiler_and_wrappers_are_only_data) { + Fixture f; + const std::string marker_tool = "#!/bin/sh\nprintf 'unexpected launch' >> \"${0%/*}/marker\"\n"; + make_tool(f.tool, marker_tool); + make_tool(f.temp.path() / "ccache", marker_tool); + make_tool(f.temp.path() / "plugin-marker", marker_tool); + write(f.temp.path() / "marker", "untouched"); + TrustPolicy policy; + const auto gen = f.install(policy, compiler_use); + auto checked = policy.check_tool(f.root, compiler_use, f.tool, gen); + require(checked.has_value()); + const std::vector wrappers{"ccache", "sccache"}; + const std::vector command{f.tool.string(), + "-c", + "-std=c++26", + "-freflection", + "-D", + "WITH_SPACES=a b", + "-UUNUSED", + "-I" + f.root.string(), + "-isystem", + f.other.string(), + "-x", + "c++", + (f.root / "some source.cpp").string()}; + auto report = + classify_and_unwrap_command(command, wrappers, checked->identity, CompilerDriver::gcc); + expect(report.allowed && report.classification == FlagClassification::safe && + report.unwrapped_argv == command); + auto wrapped = command; + wrapped.insert(wrapped.begin(), {(f.temp.path() / "ccache").string(), "sccache"}); + report = classify_and_unwrap_command(wrapped, wrappers, checked->identity, CompilerDriver::gcc); + expect(report.allowed && report.classification == FlagClassification::transparent_wrapper); + expect(report.unwrapped_argv == command && + report.unwrapped_wrappers == std::vector{wrapped[0], wrapped[1]}); + wrapped.push_back("-fplugin=" + (f.temp.path() / "plugin-marker").string()); + report = classify_and_unwrap_command(wrapped, wrappers, checked->identity, CompilerDriver::gcc); + expect(!report.allowed && + report.classification == FlagClassification::execution_bearing_plugin); + std::ifstream marker(f.temp.path() / "marker"); + std::string contents; + std::getline(marker, contents); + expect(contents == "untouched"); +} + +VOID_TEST(WorkspaceTests, unresolved_or_execution_bearing_argv_is_refused) { + Fixture f; + auto identity = inspect_tool_identity(f.tool); + require(identity.has_value()); + const std::vector wrappers{"ccache", "custom-wrapper"}; + auto classify = [&](std::vector argv, + CompilerDriver driver = CompilerDriver::gcc) { + return classify_and_unwrap_command(argv, wrappers, *identity, driver); + }; + using enum FlagClassification; + auto blocked = [&](std::vector middle, FlagClassification reason) { + std::vector cmd{f.tool.string(), "-c"}; + cmd.insert(cmd.end(), middle.begin(), middle.end()); + cmd.push_back((f.root / "a.cpp").string()); + auto report = classify(cmd); + expect(!report.allowed && report.classification == reason && + report.unwrapped_argv.empty() && !report.reason.empty()); + }; + for (auto flag : {"-fplugin=marker", "-fpass-plugin=marker", "-load"}) + blocked({flag}, execution_bearing_plugin); + for (auto flag : {"-Xclang", "-Wp,marker", "-Wa,marker", "-Wl,marker", "-B/tools", + "-specs=marker", "--config=marker"}) + blocked({flag}, suspicious_toolchain_override); + blocked({"-wrapper=marker"}, execution_bearing_wrapper); + blocked({"@nested.rsp"}, unresolved_response_file); + blocked({"-I", "@include.rsp"}, unresolved_response_file); + blocked({"-isystem", "-fplugin=marker"}, unsupported_operand); + blocked({"-x", "assembler"}, unsupported_operand); + blocked({"-D", "-Xclang"}, unsupported_operand); + for (auto flag : {"-finvented-mode", "-o", "--", "-cc1", "-mllvm", "--target=elsewhere"}) + blocked({flag}, unsupported_option); + blocked({"relative.cpp"}, unsupported_operand); + blocked({std::string("a\0b", 3)}, invalid_command); + expect(classify({"g++", "-c", (f.root / "a.cpp").string()}).classification == + unapproved_compiler_path); + expect(classify({"custom-wrapper", f.tool.string(), "-c", (f.root / "a.cpp").string()}) + .classification == execution_bearing_wrapper); + expect(classify({f.tool.string(), "-c", (f.root / "a.cpp").string()}, CompilerDriver::unknown) + .classification == unsupported_driver); + expect(!classify({f.tool.string(), (f.root / "a.cpp").string()}).allowed); +} diff --git a/tools/prepare-gcc-observer b/tools/prepare-gcc-observer new file mode 100755 index 0000000..d23801e --- /dev/null +++ b/tools/prepare-gcc-observer @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Build the local stock GCC occurrence observer with a scrubbed environment. + +The artifact is a development-only GCC plugin. Its ELF dynamic section is +checked before publication: no mutable or relative loader search entries, and +every DT_NEEDED resolves inside the selected compiler's immutable runtime. +""" + +import argparse +import hashlib +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + + +ROOT = Path(__file__).resolve().parents[1] +SOURCE = ROOT / "experiments/frontend/gcc-observer/Observer.cpp" +STORE = re.compile(r"/nix/store/[0-9a-z]{32}-[A-Za-z0-9+._?=-]+") +ENV_DROP = re.compile(r"^(NIX_|LD_|LIBRARY_PATH$|CPATH$|C_INCLUDE_PATH$|CPLUS_INCLUDE_PATH$|" + r"GCC_EXEC_PREFIX$|COMPILER_PATH$|.*FLAGS$|.*_FLAGS$)") + + +def scrubbed_environment(temp): + base = {"PATH": "/usr/bin:/bin", "LC_ALL": "C", "TZ": "UTC0", "TMPDIR": str(temp)} + for key, value in os.environ.items(): + if key not in base and not ENV_DROP.match(key): + base[key] = value + return base + + +def run(argv, env, what, timeout=120): + result = subprocess.run(argv, env=env, stdin=subprocess.DEVNULL, capture_output=True, + text=True, timeout=timeout) + if result.returncode: + raise ValueError(f"{what} exited {result.returncode}: {result.stderr[-1200:]}") + return result + + +def find_gmp(compiler, env, explicit): + if explicit: + header = Path(explicit).resolve(strict=True) + if header.is_dir(): + header /= "gmp.h" + if not header.is_file(): + raise ValueError(f"no gmp.h under {explicit}") + return header.parent + candidates = sorted(Path("/nix/store").glob("*-gmp-with-cxx-*-dev/include/gmp.h")) + if not candidates: + raise ValueError("could not locate a GMP development header; pass --gmp-include") + digests = set() + for header in candidates: + with header.open("rb") as stream: + digests.add(hashlib.file_digest(stream, "sha256").hexdigest()) + if len(digests) != 1: + raise ValueError("multiple distinct GMP headers are installed; pass --gmp-include") + return candidates[0].parent + + +def dynamic_section(readelf, elf): + result = subprocess.run([readelf, "-d", str(elf)], capture_output=True, text=True, + timeout=30) + if result.returncode: + raise ValueError(f"readelf failed for {elf}: {result.stderr[-400:]}") + needed, runpath, rpath = [], [], [] + for line in result.stdout.splitlines(): + if "(NEEDED)" in line: + needed.append(line.rsplit("[", 1)[1].rstrip("]")) + elif "(RUNPATH)" in line: + runpath.extend(line.split(":", 1)[1].strip().strip("[]").split(":")) + elif "(RPATH)" in line: + rpath.extend(line.split(":", 1)[1].strip().strip("[]").split(":")) + return needed, runpath, rpath + + +def soname(readelf, library): + result = subprocess.run([readelf, "-d", str(library)], capture_output=True, text=True, + timeout=30) + match = re.search(r"\(SONAME\).*\[(.+)\]", result.stdout) + return match.group(1) if match else None + + +def verify_elf(readelf, artifact, frontend, compiler, env): + needed, runpath, rpath = dynamic_section(readelf, artifact) + if rpath: + raise ValueError(f"rejected RPATH in {artifact}: {rpath}") + closure = set() + package = Path(*frontend.parts[:4]) + nix_store = shutil.which("nix-store") + if nix_store and package.is_dir(): + closure = {Path(p) for p in run([nix_store, "-qR", str(package)], env, + "nix-store query", timeout=60).stdout.splitlines()} + if not closure: + raise ValueError("could not establish the selected compiler runtime closure") + for entry in runpath: + path = Path(entry) + match = STORE.match(entry) + if (not entry or not path.is_absolute() or ".." in path.parts or match is None + or not path.is_dir()): + raise ValueError(f"unapproved loader search entry {entry!r}") + if Path(match.group(0)) not in closure: + raise ValueError(f"loader search entry outside the compiler runtime: {entry}") + if not needed: + raise ValueError("the observer has no dynamic dependencies") + frontend_runpath = dynamic_section(readelf, frontend)[1] + search = [*frontend_runpath, *[str(p) for p in sorted(closure) if (p / "lib").is_dir()]] + for name in needed: + printed = run([compiler, f"-print-file-name={name}"], env, "compiler search").stdout.strip() + candidates = [Path(printed)] if printed and printed != name else [] + candidates += [Path(directory) / name for directory in search] + resolved = None + for candidate in candidates: + if not candidate.is_file(): + continue + actual = candidate.resolve() + match = STORE.match(str(actual)) + if match is None or Path(match.group(0)) not in closure: + continue + if soname(readelf, candidate) == name: + resolved = actual + break + if resolved is None: + raise ValueError(f"unresolved dynamic dependency {name}") + return needed, runpath + + +def plugin_abi(include): + text = (include / "plugin-version.h").read_text(encoding="utf-8") + values = dict(re.findall(r"#define\s+GCCPLUGIN_VERSION_(\w+)\s+(\d+)", text)) + return f"{values['MAJOR']}.{values['MINOR']}.{values['PATCHLEVEL']}" + + +def prepare(args): + compiler = Path(shutil.which(args.cxx) or "").resolve(strict=True) + readelf = shutil.which("readelf") + if not readelf: + raise ValueError("readelf is required") + if args.inspect: + with tempfile.TemporaryDirectory(prefix="vls-gcc-observer-") as temp: + env = scrubbed_environment(Path(temp)) + frontend = Path(run([compiler, "-print-prog-name=cc1plus"], env, + "frontend search").stdout.strip()).resolve(strict=True) + needed, runpath = verify_elf(readelf, Path(args.inspect).resolve(strict=True), + frontend, compiler, env) + print(f"needed {', '.join(needed)}") + print(f"runpath {':'.join(runpath) if runpath else '(none)'}") + return + if not args.output: + raise ValueError("--output is required unless --inspect is used") + if not SOURCE.is_file(): + raise ValueError(f"missing observer source {SOURCE}") + output = Path(args.output).absolute() + output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="vls-gcc-observer-", dir=output.parent) as temp: + work = Path(temp) + env = scrubbed_environment(work) + plugin = Path(run([compiler, "-print-file-name=plugin"], env, "plugin search").stdout.strip()) + include = plugin / "include" + if not (include / "gcc-plugin.h").is_file(): + raise ValueError(f"no GCC plugin headers under {include}") + gmp = find_gmp(compiler, env, args.gmp_include) + version = run([compiler, "-dumpfullversion"], env, "compiler version").stdout.strip() + target = run([compiler, "-dumpmachine"], env, "compiler target").stdout.strip() + frontend = Path(run([compiler, "-print-prog-name=cc1plus"], env, + "frontend search").stdout.strip()).resolve(strict=True) + temporary = work / "occurrences.so" + run([compiler, "-std=c++17", "-fPIC", "-fno-rtti", "-fno-exceptions", "-shared", + "-I", str(include), "-I", str(gmp), str(SOURCE), "-o", str(temporary)], + env, "observer build") + needed, runpath = verify_elf(readelf, temporary, frontend, compiler, env) + with temporary.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + os.chmod(temporary, 0o755) + os.replace(temporary, output) + print(f"GCC {version} ({target}) plugin ABI {plugin_abi(include)}") + print(f"sha256 {digest}") + print(f"needed {', '.join(needed)}") + print(f"runpath {':'.join(runpath) if runpath else '(none)'}") + print(output) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cxx", default="g++") + parser.add_argument("--gmp-include", type=Path, + help="GMP development include directory (default: verified Nix candidate)") + parser.add_argument("--output", type=Path, + help="published observer artifact (required for a build)") + parser.add_argument("--inspect", type=Path, + help="validate the dynamic section of an existing artifact and exit") + args = parser.parse_args() + prepare(args) + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, subprocess.SubprocessError) as exc: + raise SystemExit(f"prepare-gcc-observer: {exc}") diff --git a/tools/prepare-gcc-profile b/tools/prepare-gcc-profile new file mode 100755 index 0000000..a2fbd54 --- /dev/null +++ b/tools/prepare-gcc-profile @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Prepare a local Linux/Nix stock GCC diagnostics profile in the project's dev shell.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import shutil +import subprocess +import tempfile + + +def run(args): + p = subprocess.run(args, capture_output=True, text=True, timeout=30) + if p.returncode: + raise ValueError(f"{Path(args[0]).name} exited {p.returncode}: {p.stderr[-600:]}") + return p + + +def store_package(path): + parts = path.parts + if (len(parts) < 4 or parts[:3] != ("/", "nix", "store") + or not re.fullmatch(r"[0-9a-z]{32}-[A-Za-z0-9+._?=-]+", parts[3])): + raise ValueError(f"expected an immutable Nix store input for {path.name}") + return Path(*parts[:4]) + + +def executable(name): + selected = shutil.which(name) + if not selected: + raise ValueError(f"could not locate {name}") + path = Path(selected).resolve(strict=True) + store_package(path) + with path.open("rb") as f: + return {"path": str(path), "sha256": hashlib.file_digest(f, "sha256").hexdigest()} + + +def plan(command): + lines = run(command).stderr.splitlines() + stages = [shlex.split(line) for line in lines if line.lstrip().startswith(("/", '"/'))] + if len(stages) != 1 or Path(stages[0][0]).name != "cc1plus": + raise ValueError("expected exactly one GCC C++ frontend in the driver dry run") + return stages[0] + + +def prepare(cxx, observer=None): + driver, bwrap, tracer, limiter = (executable(name) for name in (cxx, "bwrap", "strace", "prlimit")) + version = run([driver["path"], "-dumpfullversion"]).stdout.strip() + target = run([driver["path"], "-dumpmachine"]).stdout.strip() + if version != "16.2.0" or not re.fullmatch(r"[a-zA-Z0-9_-]{1,128}", target): + raise ValueError("the verified profile requires GCC 16.2.0 with a known target") + probe = ["-###", "-fsyntax-only", "-fdiagnostics-format=sarif-stderr", + "-frandom-seed=vls-probe", "-std=c++26", "-freflection", "/vls-check/sample.cpp"] + reference = plan([driver["path"], *probe]) + frontend = executable(reference[0]) + roots = {store_package(Path(x["path"])) for x in (driver, frontend, tracer)} + system = {Path(reference[i + 1]) for i, word in enumerate(reference[:-1]) + if word in ("-isystem", "-idirafter", "-I")} + for path in system: + store_package(path) + if not path.is_dir(): + raise ValueError("the compiler reported a missing system include directory") + closure = set(run(["nix-store", "-qR", *sorted(roots)]).stdout.splitlines()) + if not 0 < len(closure) <= 128 or any(store_package(Path(p)) != Path(p) for p in closure): + raise ValueError("unexpected tool runtime closure") + mounts = sorted(closure | {str(p) for p in system if str(store_package(p)) not in closure}) + key = "NIX_CFLAGS_COMPILE_" + target.replace("-", "_") + # Reproduce the cc-wrapper's target-specific include/seed settings with a closed environment. + words = shlex.split(os.environ.get(key, os.environ.get("NIX_CFLAGS_COMPILE", ""))) + i = 0 + while i < len(words): + if re.fullmatch(r"-frandom-seed=[A-Za-z0-9._-]+", words[i]): + i += 1 + elif i + 1 < len(words) and words[i] in ("-isystem", "-idirafter", "-I"): + p = Path(words[i + 1]) + store_package(p) + if p not in system or not re.fullmatch(r"/[A-Za-z0-9_+./=-]+", str(p)): + raise ValueError("unverified toolchain include option") + i += 2 + else: + raise ValueError("the toolchain includes an unsupported environment flag") + sandbox = [bwrap["path"], "--unshare-all", "--die-with-parent", "--new-session", + "--clearenv", "--setenv", "LC_ALL", "C", "--setenv", "TZ", "UTC0", + "--setenv", "TZDIR", str(Path(frontend["path"]).parent), + "--dev", "/dev", "--tmpfs", "/tmp"] + for mount in mounts: + sandbox += ["--ro-bind", mount, mount] + sandbox += ["--setenv", key, " ".join(words), "--dir", "/vls-check", "--chdir", "/vls-check", "--"] + for flags in (probe, [*probe, "-DPROFILE_CHECK=1", "-pthread", "-O2", "-fPIC"]): + if plan([driver["path"], *flags]) != plan([*sandbox, driver["path"], *flags]): + raise ValueError("isolated compiler options differ from the selected dev shell") + data = {"schema": 1, "version": version, "target": target, "driver": driver, + "frontend": frontend, "bubblewrap": bwrap, "strace": tracer, "prlimit": limiter, "mounts": mounts, + "toolchainFlags": words} + if observer is not None: + path = Path(observer).resolve(strict=True) + if not path.is_absolute() or not path.is_file(): + raise ValueError("--observer must be an absolute regular artifact") + with path.open("rb") as binary: + data["observer"] = {"path": str(path), "sha256": hashlib.file_digest(binary, "sha256").hexdigest()} + return data + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cxx", default="g++") + parser.add_argument("--observer", type=Path, + help="absolute stock occurrence observer artifact to select") + parser.add_argument("--output", type=Path, default=Path("build/gcc-profile.json")) + args = parser.parse_args() + data = prepare(args.cxx, args.observer) + output = args.output.absolute() + output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(mode="w", dir=output.parent, delete=False) as f: + try: + json.dump(data, f, indent=2) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + os.replace(f.name, output) + finally: + Path(f.name).unlink(missing_ok=True) + print(f"GCC {data['version']} ({data['target']}), verified {len(data['mounts'])} mounts. {output}") + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, subprocess.SubprocessError) as exc: + raise SystemExit(f"prepare-gcc-profile: {exc}") diff --git a/tools/prepare-private-gcc b/tools/prepare-private-gcc new file mode 100755 index 0000000..cbd9270 --- /dev/null +++ b/tools/prepare-private-gcc @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Reproduce the private GCC 16.2.0 frontend from the versioned compiler patches.""" + +import argparse +import os +from pathlib import Path +import shlex +import shutil +import subprocess +import sys +import tempfile + + +ROOT = Path(__file__).resolve().parents[1] +PATCHES = ROOT / "compiler-patches/gcc-16.2.0" +VERSION = "16.2.0" +TOOLS = {"CC": "gcc", "CXX": "g++", "AR": "ar", "AS": "as", "LD": "ld", "NM": "nm", + "RANLIB": "ranlib", "STRIP": "strip", "OBJCOPY": "objcopy", "OBJDUMP": "objdump", + "READELF": "readelf"} +OPTIMIZATION = {"CFLAGS": "-O1 -g1", "CXXFLAGS": "-O1 -g1"} + + +def configure_options(prefix): + lines = (PATCHES / "configure.args").read_text(encoding="utf-8").splitlines() + text = " ".join(line for line in lines if line and not line.startswith("#")) + return shlex.split(text.replace("@PREFIX@", str(prefix))) + + +def patch_state(source, patch): + """Forward and reverse dry runs distinguish a pristine, applied or foreign tree.""" + base = ["patch", "--dry-run", "-p1", "--directory", str(source), "-i", str(patch)] + if subprocess.run([*base, "--forward"], capture_output=True).returncode == 0: + return "unpatched" + if subprocess.run([*base, "--reverse"], capture_output=True).returncode == 0: + return "already-applied" + return "mismatch" + + +def validate_series(source, patches): + """Apply the ordered series to a scratch copy: patches depend on their predecessors.""" + with tempfile.TemporaryDirectory(prefix="vls-gcc-series-") as temp: + scratch = Path(temp) / "source" + shutil.copytree(source, scratch, symlinks=True) + results = [] + for patch in patches: + if patch_state(scratch, patch) == "already-applied": + results.append((patch.name, True)) + continue + applied = subprocess.run( + ["patch", "-p1", "--directory", str(scratch), "-i", str(patch)], + capture_output=True) + results.append((patch.name, applied.returncode == 0)) + if applied.returncode != 0: + break + return results + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, default=Path("build/gcc-gate/gcc-16.2.0"), + help="GCC 16.2.0 source tree") + parser.add_argument("--output", type=Path, default=Path("build/private-gcc"), + help="private build root (source copy, build and install)") + parser.add_argument("--jobs", type=int, default=os.cpu_count() or 1) + parser.add_argument("--check-only", action="store_true", + help="validate the source and patch set, print the recipe, build nothing") + args = parser.parse_args() + try: + source = args.source.resolve(strict=True) + version = source / "gcc/BASE-VER" + if not version.is_file() or version.read_text(encoding="utf-8").strip() != VERSION: + raise ValueError(f"expected a GCC {VERSION} source tree at {source}") + patches = sorted(PATCHES.glob("*.patch")) + if not patches: + raise ValueError(f"no patches under {PATCHES}") + states = {} + for patch in patches: + states[patch.name] = patch_state(source, patch) + print(f"{patch.name}: {states[patch.name]}") + if not args.check_only and any(state == "mismatch" for state in states.values()): + raise ValueError("the patch set does not match this source tree") + prefix = args.output.absolute() / "install" + command = [str(source / "configure"), *configure_options(prefix)] + print("configure:", shlex.join(command)) + if args.check_only: + series = validate_series(source, patches) + for name, ok in series: + print(f"series {name}: {'ok' if ok else 'failed'}") + if len(series) != len(patches) or not all(ok for _, ok in series): + raise ValueError("the ordered patch series does not apply") + print(f"check passed: {len(patches)} patches, GCC {VERSION}, prefix {prefix}") + return 0 + output = args.output.absolute() + tree, build = output / "source", output / "build" + if output.exists(): + raise ValueError(f"output already exists: {output}") + shutil.copytree(source, tree, symlinks=True) + for patch in patches: + if states[patch.name] == "already-applied": + continue + subprocess.run(["patch", "-p1", "--directory", str(tree), "-i", str(patch)], + check=True) + build.mkdir(parents=True) + environment = {**os.environ, **TOOLS, **OPTIMIZATION} + subprocess.run(command, cwd=build, env=environment, check=True) + subprocess.run(["make", f"-j{args.jobs}"], cwd=build, check=True) + print(f"private GCC built under {build}; selected frontend is in gcc/cc1plus") + return 0 + except (OSError, ValueError, subprocess.SubprocessError) as error: + print(f"prepare-private-gcc: {error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/prepare-voidlibrary b/tools/prepare-voidlibrary new file mode 100755 index 0000000..d1ead16 --- /dev/null +++ b/tools/prepare-voidlibrary @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""Prepare the tracked VoidLibrary sources consumed by VLS's native VBS recipe.""" + +import argparse +from contextlib import ExitStack, contextmanager +import fcntl +import hashlib +import json +import os +from pathlib import Path +import re +import stat +import subprocess +import sys +import tempfile + + +UPSTREAM = "https://git.faumaray.com/Void/VoidLibrary.git" +PROJECT = Path(__file__).resolve().parents[1] + +# The VBS recipe's module closure, including the Crypto and Text foundations. +MODULES = ("Async", "Configuration", "Core", "Crypto", "Data", "Functional", "LogState", + "Math", "System", "Testing", "Text", "Time", "Unicode") +SOURCE_DIRS = {f"src/{module}" for module in MODULES} +PUBLIC_DIRS = {f"include/Void/{module}" for module in MODULES if module != "LogState"} +SUPPORT = {"include/Void/Detail/Enum.hpp", "include/Void/Log/Log.hpp", "include/Void/Stacktrace/Color.hpp"} +# These co-located public headers belong to optional modules outside the closure. +OPTIONAL = { + "include/Void/Configuration/ReloadController.hpp", "include/Void/Crypto/AsyncHash.hpp", + "include/Void/System/AsyncProcess.hpp", "include/Void/System/AsyncWatcher.hpp", +} +REQUIRED = SUPPORT | { + "include/Void/Configuration/Argparse.hpp", "include/Void/Core/Hash.hpp", + "include/Void/Crypto/Crypto.hpp", "include/Void/Data/StrictJson.hpp", + "include/Void/System/Process.hpp", "include/Void/Testing/Test.hpp", + "include/Void/Text/Url.hpp", "include/Void/Unicode/Utf.hpp", + "src/Configuration/Argparse.cpp", "src/Crypto/Crypto.cpp", "src/LogState/State.cpp", + "src/System/Process.cpp", "src/Testing/Main.cpp", +} +SCOPES = sorted({"build.cpp"} | SOURCE_DIRS | PUBLIC_DIRS | SUPPORT) +PRIVATE_NAMES = {"keys", "secrets", "credentials"} +DIRECTORY = os.O_DIRECTORY | os.O_NOFOLLOW | os.O_RDONLY + + +class PreparationError(Exception): + pass + + +def git(repo, *args): + # Plumbing reads raw objects/index entries. Never check out or run a dependency's + # filters, fsmonitor, hooks, submodule commands or lazy object fetches. + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + env.update(GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1", GIT_NO_LAZY_FETCH="1", + GIT_NO_REPLACE_OBJECTS="1", GIT_OPTIONAL_LOCKS="0", + GIT_ALLOW_PROTOCOL="https" if args[0] == "fetch" else "", + GIT_TERMINAL_PROMPT="0") + cmd = ["git", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", + "-c", "credential.helper=", "-C", str(repo), *args] + result = subprocess.run(cmd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL) + if result.returncode: + raise PreparationError(f"git {args[0]} failed (exit {result.returncode})") + return result.stdout + + +def selected(path): + if path in SUPPORT: + return True + parent, _, name = path.rpartition("/") + if (not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*\.(cpp|h|hh|hpp|hxx|ipp|inl|tpp)", name) + or name.partition(".")[0].lower() in PRIVATE_NAMES): + return False + parts = parent.split("/") + if any(not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_-]*", part) + or part.lower() in PRIVATE_NAMES for part in parts): + return False + # VBS recursively collects translation units under each selected module. + return ("/".join(parts[:2]) in SOURCE_DIRS or + ("/".join(parts[:3]) in PUBLIC_DIRS and not name.endswith(".cpp") and path not in OPTIONAL)) + + +def inventory(repo, revision=None): + if revision: + rows = git(repo, "ls-tree", "-rz", revision, "--", *SCOPES) + else: + rows = git(repo, "ls-files", "--stage", "-z", "--", *SCOPES) + blobs = {} + for row in rows.split(b"\0"): + if not row: + continue + fields, name = row.split(b"\t", 1) + path = os.fsdecode(name) + if path == "build.cpp" or path.startswith("build.cpp/"): + raise PreparationError("tracked root build.cpp requires recipe review") + if not selected(path): + if path.endswith(".cpp") and "/".join(path.split("/")[:2]) in SOURCE_DIRS: + raise PreparationError("unsupported tracked translation unit in a recipe source directory") + continue + mode, second, third = fields.split() + if mode not in (b"100644", b"100755") or (not revision and third != b"0"): + raise PreparationError("selected Git input is a link, special file or unmerged entry") + blobs[path] = (mode, (third if revision else second).decode("ascii")) + return blobs + + +def commit(repo, ref): + value = git(repo, "rev-parse", "--verify", ref + "^{commit}").strip().decode("ascii") + if not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", value): + raise PreparationError("invalid Git revision") + return value + + +@contextmanager +def directory(path, parent=None): + fd = os.open(path, DIRECTORY, dir_fd=parent) + try: + yield fd + finally: + os.close(fd) + + +def local_file(root, path): + # Pin every directory component and refuse links on every open, including the + # leaf. O_NONBLOCK keeps a substituted FIFO from hanging before fstat. + with ExitStack() as stack: + parts = path.split("/") + for part in parts[:-1]: + root = stack.enter_context(directory(part, root)) + fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=root) + with os.fdopen(fd, "rb") as stream: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: + raise PreparationError("local input must be a regular, singly linked file") + stamp = (info.st_dev, info.st_ino, info.st_size, info.st_ctime_ns, info.st_mtime_ns) + mode = b"100755" if info.st_mode & stat.S_IXUSR else b"100644" + return stream.read(), stamp, mode + + +def materialize(work, tree, source): + local = source is not None + if local: + repo = Path(source).resolve(strict=True) + top = os.fsdecode(git(repo, "rev-parse", "--show-toplevel").removesuffix(b"\n")) + if Path(top) != repo: + raise PreparationError("--source must name the root of a Git working tree") + ref = "HEAD" + else: + repo = work / "upstream.git" + git(work, "init", "--bare", "--template=", str(repo)) + git(repo, "fetch", "--no-tags", "--no-recurse-submodules", "--no-auto-maintenance", + "--depth=1", UPSTREAM, "refs/heads/main") + ref = "FETCH_HEAD" + + revision = commit(repo, ref) + committed = inventory(repo, revision) + inputs = inventory(repo) if local else committed + if not REQUIRED.issubset(inputs) or not PUBLIC_DIRS.issubset({p.rpartition("/")[0] for p in inputs}): + raise PreparationError("incomplete VoidLibrary recipe inputs for the required modules") + dirty = inputs != committed + digest = hashlib.sha256() + captured = {} + with ExitStack() as stack: + root = stack.enter_context(directory(repo)) if local else None + for path, (mode, oid) in sorted(inputs.items()): + if local: + data, stamp, file_mode = local_file(root, path) + algorithm = "sha1" if len(oid) == 40 else "sha256" + blob = hashlib.new(algorithm, f"blob {len(data)}\0".encode()) + blob.update(data) + dirty |= file_mode != mode or blob.hexdigest() != oid + else: + data = git(repo, "cat-file", "blob", oid) + target = tree / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + content_hash = hashlib.sha256(data).digest() + digest.update(path.encode("ascii") + b"\0" + content_hash) + if local: + captured[path] = (stamp, content_hash) + if local: + # All captured files existed together between these two passes. A rename, + # write, symlink substitution or tracking change invalidates the capture. + for path, expected in captured.items(): + data, stamp, _ = local_file(root, path) + if (stamp, hashlib.sha256(data).digest()) != expected: + raise PreparationError("local sources changed during preparation; retry") + if (not os.path.samestat(os.fstat(root), repo.stat()) or commit(repo, ref) != revision + or inventory(repo) != inputs): + raise PreparationError("local Git checkout changed during preparation; retry") + (tree / "src/Core").mkdir(parents=True, exist_ok=True) # VBS recipe detection; Core is header-only. + provenance = {"format": 1, "source_kind": "local" if local else "main", "revision": revision, + "dirty": dirty, "content_sha256": digest.hexdigest()} + if local: + try: + provenance["source_path"] = os.fsencode(repo).decode("utf-8") + except UnicodeDecodeError: + raise PreparationError("local source path must be valid UTF-8") from None + else: + provenance["source_url"] = UPSTREAM + metadata = (json.dumps(provenance, sort_keys=True) + "\n").encode("utf-8") + if len(metadata) > 32768: + raise PreparationError("provenance exceeds 32 KiB") + (tree / "provenance.json").write_bytes(metadata) + return hashlib.sha256(metadata).hexdigest() + + +def check_existing(tree, target): + # Only read expected regular files in the tool's store. Reject any extra + # entry (especially a descriptor) before selecting an existing generation. + for base, dirs, files in os.walk(tree): + peer = target / Path(base).relative_to(tree) + info = peer.lstat() + if (info.st_uid != os.geteuid() or info.st_mode != (stat.S_IFDIR | 0o555) + or set(os.listdir(peer)) != set(dirs + files)): + raise PreparationError("existing generation has unexpected entries or permissions") + for name in files: + src, dst = Path(base) / name, peer / name + info = dst.lstat() + if (info.st_uid != os.geteuid() or info.st_nlink != 1 or info.st_mode != (stat.S_IFREG | 0o444) + or info.st_size != src.stat().st_size + or src.read_bytes() != dst.read_bytes()): + raise PreparationError("existing generation has unexpected file contents or permissions") + + +def prepare(source): + build = PROJECT / "build" + store = build / "voidlibrary" + sources = store / "sources" + for path in (build, store, sources): + path.mkdir(mode=0o700, exist_ok=True) + info = path.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o022: + raise PreparationError(f"expected an owned directory protected from other writers: {path}") + # Stage beside the final directory. Renaming a sealed directory across parents + # can require write access to its ".." entry. + with (tempfile.TemporaryDirectory(dir=store, prefix=".prepare-") as temp, + tempfile.TemporaryDirectory(dir=sources, prefix=".stage-") as stage): + work, tree = Path(temp), Path(stage) + key = materialize(work, tree, source) + target = sources / key + with directory(store) as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + current = store / "current" + if os.path.lexists(current) and (not current.is_symlink() or + not re.fullmatch(r"sources/[0-9a-f]{64}", os.readlink(current))): + raise PreparationError("current is outside the preparation tool's managed layout") + if os.path.lexists(target): + check_existing(tree, target) + else: + for base, _, files in os.walk(tree, topdown=False): + for name in files: + (Path(base) / name).chmod(0o444) + Path(base).chmod(0o555) + tree.rename(target) + link = work / "current" + link.symlink_to(Path("sources") / key) + link.replace(current) + return target + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, + epilog="Defaults to the official refs/heads/main. Prints the immutable source directory " + "and atomically points build/voidlibrary/current at it. Local dirty status covers " + "the selected tracked build inputs.", + ) + parser.add_argument("--source", default=os.environ.get("VLS_VOID_SOURCE_DIR") or None, + metavar="CHECKOUT", help="development checkout (also VLS_VOID_SOURCE_DIR)") + try: + print(prepare(parser.parse_args().source)) + except (PreparationError, OSError) as exc: + sys.exit("prepare-voidlibrary: " + (exc.strerror if isinstance(exc, OSError) else str(exc)))