Files
carbon-lang/toolchain/language_server/handle_formatting.cpp
T
Richard Smith 03939a9223 Add language server support for SemIR in testdata. (#7803)
Add hover cards and jump to declaration / definition / reference for the
formatted SemIR that appears in check tests. This is done by adding a
heuristic "parser" for SemIR to the language server. The
cross-references are strictly best-effort, since this is just a tool for
Carbon developers, not a user-facing facility.

A couple of other changes made along the way:

* file_test tests with an AUTOUPDATE-SPLIT no longer look for CHECK:
lines outside that split. This was motivated by the tests for this new
facility including CHECK: lines as part of the test input.
* An agent skill for working on the language server, tracking some
things that cost Claude time when working on this.

Assisted-by: Claude via Antigravity
2026-09-23 23:44:32 +00:00

64 lines
1.9 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <string>
#include <utility>
#include <vector>
#include "common/raw_string_ostream.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "toolchain/format/format.h"
#include "toolchain/language_server/handle.h"
namespace Carbon::LanguageServer {
// Returns the range covering the entire document text.
static auto GetFullDocumentRange(llvm::StringRef text) -> clang::clangd::Range {
int line_count = llvm::count(text, '\n') + 1;
return clang::clangd::Range{
.start = {.line = 0, .character = 0},
.end = {.line = line_count, .character = 0},
};
}
auto HandleFormatting(
Context& context, const clang::clangd::DocumentFormattingParams& params,
llvm::function_ref<
auto(llvm::Expected<std::vector<clang::clangd::TextEdit>>)->void>
on_done) -> void {
auto* file = context.LookupFile(params.textDocument.uri.file());
if (!file) {
return;
}
if (file->is_test_file()) {
// A test file isn't Carbon source, so it has no parse tree to format from,
// and reformatting one as if it were would destroy it.
on_done(std::vector<clang::clangd::TextEdit>());
return;
}
RawStringOstream out;
if (!Format::Format(file->tokens(), out)) {
out.clear();
on_done(std::vector<clang::clangd::TextEdit>());
return;
}
std::string formatted_text = out.TakeStr();
if (formatted_text == file->text()) {
on_done(std::vector<clang::clangd::TextEdit>());
return;
}
std::vector<clang::clangd::TextEdit> edits;
edits.push_back(clang::clangd::TextEdit{
.range = GetFullDocumentRange(file->text()),
.newText = std::move(formatted_text),
});
on_done(std::move(edits));
}
} // namespace Carbon::LanguageServer