Serve formatting through clang-format

Per the user's decision, textDocument/formatting runs clang-format as a
bounded child process with a 5s deadline and capped streams. A bounded
core builds the arguments (workspace .clang-format when present,
otherwise the LSP tab options as an explicit LLVM style) and the
whole-document edit, refusing output over 32 MiB. Registered feature
tests cover the arguments, bounds and edit shape; a real stdio session
formatted a misindented document. clang-format becomes a runtime
dependency of formatting.
This commit is contained in:
faumaray committed 2026-12-05 21:30:44 +03:00
1 parent 7acbfc4029
commit 3344a9f170
12 files changed
+247 -5

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ add_library(vls_protocol STATIC src/Protocol/Framing.cpp src/Protocol/Json.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/features/DocumentSymbols.cpp src/features/TextStructure.cpp src/features/CodeActions.cpp src/features/SemanticTokens.cpp src/features/InlayHints.cpp src/features/FileOperations.cpp src/features/IncludeUpdate.cpp src/features/CallHierarchy.cpp src/features/CodeLens.cpp src/features/DocumentLinks.cpp src/debug/live/LiveSession.cpp src/modules/ModuleWorkQueue.cpp src/modules/GccScan.cpp src/modules/ScanCommand.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/features/DocumentSymbols.cpp src/features/TextStructure.cpp src/features/CodeActions.cpp src/features/SemanticTokens.cpp src/features/InlayHints.cpp src/features/FileOperations.cpp src/features/IncludeUpdate.cpp src/features/CallHierarchy.cpp src/features/CodeLens.cpp src/features/DocumentLinks.cpp src/features/Formatting.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 Void::Text Void::Crypto Void::System)
target_compile_options(vls_protocol PUBLIC -freflection PRIVATE -Wall -Wextra -Wpedantic)
+2 -1
View File
@@ -79,6 +79,7 @@ void build(Void::Build::Project &project) {
"src/features/CallHierarchy.cpp",
"src/features/CodeLens.cpp",
"src/features/DocumentLinks.cpp",
"src/features/Formatting.cpp",
"src/debug/live/LiveSession.cpp",
"src/modules/ModuleWorkQueue.cpp",
"src/modules/GccScan.cpp",
@@ -162,7 +163,7 @@ void build(Void::Build::Project &project) {
"tests/features/SemanticTokensTests.cpp", "tests/features/InlayHintsTests.cpp",
"tests/features/FileOperationsTests.cpp", "tests/features/IncludeUpdateTests.cpp",
"tests/features/CallHierarchyTests.cpp", "tests/features/CodeLensTests.cpp",
"tests/features/DocumentLinksTests.cpp"});
"tests/features/DocumentLinksTests.cpp", "tests/features/FormattingTests.cpp"});
auto live_worker = project.executable("vls_live_worker_fixture");
live_worker.cxx_standard(CxxStandard::Cxx26)
.sources({"tests/debug/LiveWorkerFixture.cpp"})
+1 -1
View File
@@ -25,6 +25,7 @@ missing part. Updated December 5, 2026 after semantic tokens and inlay hints.
| textDocument/codeLens + workspace/executeCommand (`vls.showReferences`) | `vls_feature_tests`, real stdio session |
| workspace/symbol | stock occurrence corpus |
| textDocument/documentLink (quoted includes) | `vls_feature_tests`, real stdio session |
| textDocument/formatting (clang-format) | `vls_feature_tests`, real stdio session |
| workspace fileOperations (didCreate/didRename/didDelete) | `vls_feature_tests`, real stdio session |
| workspace/willRenameFiles (include updates) | `vls_feature_tests`, real stdio session |
| voidLanguageServer/analysisStatus, providerStatus | stdio corpora |
@@ -41,7 +42,6 @@ missing part. Updated December 5, 2026 after semantic tokens and inlay hints.
| Client-side application of server-issued workspace edits | rename and code actions return edits the clients apply directly |
| Applying multi-file renames through client buffers | plans can be ready; application is client work |
| richer token types | legend is one type (`function`) plus a `declaration` modifier; type tokens need compiler-provided spans |
| textDocument/formatting | no formatter is available; needs a dependency decision |
## Next slices
+1 -1
View File
@@ -103,7 +103,7 @@ ingests occurrence facts after each analysis and the server answers
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. Document symbols are served from the index by path and document highlights from same-binding occurrence facts; both are advertised and were exercised over stdio with the stock observer. Selection and folding ranges are served from immutable document snapshots with registered bounded cores. Code actions now offer the compiler's own suggested fixes (quickfix) from retained published diagnostics, with SARIF fix decoding bound to the owner snapshot. Semantic tokens encode the proven call occurrences and same-file definition names, the latter with a declaration modifier, under a bounded legend. Inlay hints project parameter types from the occurrence signature at each argument start. Workspace file-operation notifications invalidate dependent index contexts and re-queue open documents. A will-rename request returns the include updates for open documents. Reflection hover is served from a recorded snapshot file selected at launch, with the client position converted through the document snapshot. Document links resolve quoted includes to existing files without the compiler. Code lenses show index reference counts and the `vls.showReferences` command resolves them to navigation locations. Call hierarchy serves prepare and incoming calls (grouped by enclosing definition or explicitly by file) from the stock call facts. Outgoing calls are served and verified: the stock observer now reports full function extents, so nested calls are attributed to the enclosing definition. Compiler-native completion with visibility proof and deferred detail resolution 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. Document symbols are served from the index by path and document highlights from same-binding occurrence facts; both are advertised and were exercised over stdio with the stock observer. Selection and folding ranges are served from immutable document snapshots with registered bounded cores. Code actions now offer the compiler's own suggested fixes (quickfix) from retained published diagnostics, with SARIF fix decoding bound to the owner snapshot. Semantic tokens encode the proven call occurrences and same-file definition names, the latter with a declaration modifier, under a bounded legend. Inlay hints project parameter types from the occurrence signature at each argument start. Workspace file-operation notifications invalidate dependent index contexts and re-queue open documents. A will-rename request returns the include updates for open documents. Formatting is served through clang-format with the workspace style or the LSP options, bounded as a child process. Reflection hover is served from a recorded snapshot file selected at launch, with the client position converted through the document snapshot. Document links resolve quoted includes to existing files without the compiler. Code lenses show index reference counts and the `vls.showReferences` command resolves them to navigation locations. Call hierarchy serves prepare and incoming calls (grouped by enclosing definition or explicitly by file) from the stock call facts. Outgoing calls are served and verified: the stock observer now reports full function extents, so nested calls are attributed to the enclosing definition. 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
+19
View File
@@ -79,6 +79,25 @@ the upgraded snapshot (keeping `snapshot.prev.json`) and rewrites a legacy
about 25-30s in a Debug build (it passed VBS at ~27s); the full CMake run then
passed 18/18.
## December 5 formatting through clang-format
Per the user's decision, `textDocument/formatting` runs clang-format as a
bounded child process (5s deadline, capped stdin/stdout/stderr and line size,
failure returns null) from `EditorDiagnostics::format`. A bounded core
(`vls/features/Formatting.hpp`) builds the arguments and the whole-document
edit: the workspace `.clang-format` is used when present, otherwise the LSP
`tabSize`/`insertSpaces` become an explicit LLVM-based style (clang-format's
`--fallback-style` accepts only named styles). The server advertises
`documentFormattingProvider`, and output over 32 MiB is refused.
Real stdio session on `int x=1;\nint f( int a,int b ){return a+b;}\n`:
```
result: [{"newText": "int x = 1;\nint f(int a, int b) { return a + b; }\n",
"range": {"start": {"line": 0, "character": 0}, "end": {"line": 2, "character": 0}}}]
```
Registered `vls_feature_tests` grew to 101 cases. All 18 native suites and all
18 CMake tests passed. clang-format is now a runtime dependency of formatting.
## December 5 reflection hover from a recorded snapshot
Per the user's decision, `EditorDiagnostics` reflection data now comes from a
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace vls::features::formatting {
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 Edit {
Range range;
std::string replacement;
auto operator<=>(const Edit &) const = default;
};
// LSP formatting options, bounded by the server before they get here.
struct Options {
std::uint32_t tab_size{4};
bool insert_spaces{true};
};
struct Limits {
std::size_t outputBytes{32 * 1024 * 1024};
std::size_t tabSize{64};
};
// clang-format arguments. With FILE_STYLE the workspace .clang-format is used
// (--style=file); otherwise the LSP options become an explicit LLVM-based
// style. The path only names the file, nothing is read from it here.
[[nodiscard]] std::vector<std::string> arguments(const Options &, std::string_view path,
bool file_style, const Limits & = Limits{});
// A single whole-document replacement when the formatted text differs, or
// nothing when it is identical or exceeds the bound. The range end covers the
// last character of the original text.
[[nodiscard]] std::vector<Edit> edits(std::string_view original, std::string_view formatted,
const Limits & = Limits{});
} // namespace vls::features::formatting
@@ -60,6 +60,10 @@ class EditorDiagnostics {
selection_ranges(std::string_view uri, std::span<const Documents::Position>) const;
// Foldable brace blocks, comments, regions and include groups.
[[nodiscard]] Void::LanguageServer::Protocol::Json folding_ranges(std::string_view uri) const;
// Whole-document formatting through clang-format. Empty when the text is
// already formatted; null when the formatter is unavailable or failed.
[[nodiscard]] Void::LanguageServer::Protocol::Json
format(std::string_view uri, std::uint32_t tab_size, bool insert_spaces) const;
// Reference-count lenses for the records the index holds for one document.
[[nodiscard]] Void::LanguageServer::Protocol::Json code_lenses(std::string_view uri) const;
// Quick fixes suggested by the compiler for diagnostics overlapping the
+19
View File
@@ -22,6 +22,8 @@ namespace {
namespace Protocol = Void::LanguageServer::Protocol;
using Protocol::as_array;
using Protocol::as_bool;
using Protocol::as_int64;
using Protocol::as_object;
using Protocol::as_string;
using Protocol::find_member;
@@ -321,6 +323,8 @@ DispatchResult Server::handle(std::string_view body) {
{"workspace", Json{std::move(workspace)}}};
capabilities.emplace("documentLinkProvider",
Json{Json::Object{{"resolveProvider", Json{false}}}});
if (diagnostics_)
capabilities.emplace("documentFormattingProvider", Json{true});
if (diagnostics_) {
capabilities.emplace("documentSymbolProvider", Json{true});
capabilities.emplace("selectionRangeProvider", Json{true});
@@ -495,6 +499,21 @@ DispatchResult Server::handle(std::string_view body) {
}
return reply(id, "result", diagnostics_->selection_ranges(*uri, selected));
}
if (*method == "textDocument/formatting") {
if (!diagnostics_)
return error(id, -32601, "Method not found");
const auto *uri = as_string(member(member(params, "textDocument"), "uri"));
const auto *options = as_object(member(params, "options"));
const auto tab_size = options ? as_int64(find_member(*options, "tabSize")) : std::nullopt;
const auto insert_spaces =
options ? as_bool(find_member(*options, "insertSpaces")) : std::nullopt;
if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !tab_size ||
*tab_size < 0 || *tab_size > 64 || !insert_spaces)
return error(id, -32602, "Expected textDocument.uri and bounded formatting options");
return reply(
id, "result",
diagnostics_->format(*uri, static_cast<std::uint32_t>(*tab_size), *insert_spaces));
}
if (*method == "textDocument/documentLink") {
const auto *uri = as_string(member(member(params, "textDocument"), "uri"));
if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri))
+46
View File
@@ -0,0 +1,46 @@
#include <vls/features/Formatting.hpp>
#include <algorithm>
#include <ranges>
namespace vls::features::formatting {
namespace {
Position end_of(std::string_view text) {
Position position;
for (const char ch : text) {
if (ch == '\n') {
++position.line;
position.character = 0;
} else {
++position.character;
}
}
return position;
}
} // namespace
std::vector<std::string> arguments(const Options &options, std::string_view path, bool file_style,
const Limits &limits) {
std::vector<std::string> result{"--assume-filename=" + std::string{path}};
if (file_style) {
result.push_back("--style=file");
return result;
}
const auto tab_size = std::min<std::uint32_t>(options.tab_size, limits.tabSize);
result.push_back("--style={BasedOnStyle: LLVM, IndentWidth: " + std::to_string(tab_size) +
", UseTab: " + (options.insert_spaces ? "Never" : "ForIndentation") + "}");
return result;
}
std::vector<Edit> edits(std::string_view original, std::string_view formatted,
const Limits &limits) {
std::vector<Edit> result;
if (formatted.empty() || formatted.size() > limits.outputBytes)
return result;
if (formatted == original)
return result;
result.push_back({{{0, 0}, end_of(original)}, std::string{formatted}});
return result;
}
} // namespace vls::features::formatting
+42
View File
@@ -5,6 +5,7 @@
#include <vls/features/CodeLens.hpp>
#include <vls/features/Completion.hpp>
#include <vls/features/DocumentSymbols.hpp>
#include <vls/features/Formatting.hpp>
#include <vls/features/IndexNavigation.hpp>
#include <vls/features/InlayHints.hpp>
#include <vls/features/SemanticTokens.hpp>
@@ -17,6 +18,8 @@
#include <vls/navigation/Navigation.hpp>
#include <vls/scheduler/Scheduler.hpp>
#include <Void/System/Process.hpp>
#include <algorithm>
#include <array>
#include <chrono>
@@ -1041,6 +1044,45 @@ Json EditorDiagnostics::completion_resolve(const Json &item) const {
return Json{std::move(enriched)};
}
Json EditorDiagnostics::format(std::string_view uri, std::uint32_t tab_size,
bool insert_spaces) const {
const auto snapshot = state_->documents.snapshot(uri);
if (!snapshot)
return Json{nullptr};
const auto path = snapshot->identity.canonical_path.native();
Void::Process::SpawnOptions spawn;
spawn.executable = "clang-format";
std::error_code error;
const bool file_style =
fs::exists(snapshot->identity.canonical_path.parent_path() / ".clang-format", error) ||
fs::exists(state_->root / ".clang-format", error);
spawn.arguments = features::formatting::arguments({tab_size, insert_spaces}, path, file_style);
spawn.search_path = true;
spawn.working_directory = snapshot->identity.canonical_path.parent_path();
auto child = Void::Process::spawn(spawn);
if (!child)
return Json{nullptr};
auto produced = Void::Process::communicate_blocking(
*child, snapshot->text,
{.max_stdout_bytes = features::formatting::Limits{}.outputBytes,
.max_stderr_bytes = 16 * 1024,
.max_line_bytes = 64 * 1024,
.max_stdin_bytes = snapshot->text.size()},
5s, {});
if (!produced || produced->timed_out || produced->cancelled || produced->overflowed ||
!produced->status.exited || produced->status.code != 0)
return Json{nullptr};
const auto edits = features::formatting::edits(snapshot->text, produced->out);
Json::Array result;
for (const auto &edit : edits)
result.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{std::move(result)};
}
Json EditorDiagnostics::code_lenses(std::string_view uri) const {
auto &s = *state_;
const auto identity = Documents::normalize_uri(uri);
+1 -1
View File
@@ -22,7 +22,7 @@ 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 features/DocumentSymbolsTests.cpp features/TextStructureTests.cpp features/CodeActionsTests.cpp features/SemanticTokensTests.cpp features/InlayHintsTests.cpp features/FileOperationsTests.cpp features/IncludeUpdateTests.cpp features/CallHierarchyTests.cpp features/CodeLensTests.cpp features/DocumentLinksTests.cpp)
vls_test_suite(vls_feature_tests features/CompletionTests.cpp features/IndexNavigationTests.cpp features/SignatureHelpTests.cpp features/DocumentSymbolsTests.cpp features/TextStructureTests.cpp features/CodeActionsTests.cpp features/SemanticTokensTests.cpp features/InlayHintsTests.cpp features/FileOperationsTests.cpp features/IncludeUpdateTests.cpp features/CallHierarchyTests.cpp features/CodeLensTests.cpp features/DocumentLinksTests.cpp features/FormattingTests.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)
+61
View File
@@ -0,0 +1,61 @@
#include <vls/features/Formatting.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <string>
#include <vector>
namespace {
using namespace vls::features::formatting;
using Void::Testing::expect;
using Void::Testing::require;
bool contains(const std::vector<std::string> &arguments, std::string_view value) {
return std::ranges::find(arguments, value) != arguments.end();
}
} // namespace
VOID_TEST(Formatting, arguments_use_the_workspace_style_with_an_lsp_fallback) {
const auto arguments = vls::features::formatting::arguments(
Options{.tab_size = 2, .insert_spaces = true}, "/project/main.cpp", false);
expect(arguments[0] == "--assume-filename=/project/main.cpp");
expect(arguments[1].find("IndentWidth: 2") != std::string::npos);
expect(arguments[1].find("UseTab: Never") != std::string::npos);
const auto workspace =
vls::features::formatting::arguments(Options{}, "/project/main.cpp", true);
expect(workspace.size() == 2);
expect(workspace[1] == "--style=file");
}
VOID_TEST(Formatting, arguments_honor_tabs_and_bound_the_tab_size) {
const auto tabs = vls::features::formatting::arguments(
Options{.tab_size = 8, .insert_spaces = false}, "/project/main.cpp", false);
expect(tabs[1].find("UseTab: ForIndentation") != std::string::npos);
const auto bounded =
vls::features::formatting::arguments(Options{.tab_size = 1000, .insert_spaces = true},
"/project/main.cpp", false, Limits{.tabSize = 16});
expect(bounded[1].find("IndentWidth: 16") != std::string::npos);
}
VOID_TEST(Formatting, identical_text_produces_no_edit) {
expect(edits("int x = 1;\n", "int x = 1;\n").empty());
expect(edits("int x = 1;\n", "").empty());
}
VOID_TEST(Formatting, changed_text_replaces_the_whole_document) {
const std::string original = "int x=1;\nint y;\n";
const std::string formatted = "int x = 1;\nint y;\n";
const auto result = edits(original, formatted);
require(result.size() == 1);
expect(result.front().range.start == Position{0, 0});
expect(result.front().range.end == Position{2, 0});
expect(result.front().replacement == formatted);
}
VOID_TEST(Formatting, output_is_bounded) {
const auto result = edits("a\n", "formatted\n", Limits{.outputBytes = 4});
expect(result.empty());
expect(contains(arguments(Options{}, "/p/a.cpp", true), "--style=file"));
}