Files
carbon-lang/toolchain/language_server/context.cpp
T
Chandler Carruth 0072b28129 Start every diagnostic with a single message attached to the code (#8102)
This is the final step in landing the _structural_ updates to diagnostic
rendering.

The key idea here is that we want the primary diagnostic to have a
message clearly explaining the problem and attached to the code that has
that problem. This should be the starting point for readers working to
address the issue, but is rendered attached to the code snippet in
question so errors are always "in context" of the code with the error.
Everything else in a diagnostic is an additional label attached to code
to explain or help the reader understand the problem in the primary
message.

Previously, `ContextScope` resulted in some confusion here, as
diagnostic consumers turned messages into labels and made the message in
the context scope the message. In essence, this isn't a scope with
context _for_ a diagnostic (with two exceptions that should probably
have been an `AnnotationScope`), but a context within `check` where we
have a preferred message for a diagnostic emitted by general purpose
code we call into. For example, "class was forward declared here" starts
as an error, and then consumers render it as a label to make the message
from the context scope the error. We also grew an `AnnotationScope` to
handle the contextual information we want to show for a diagnostic (what
I would have assumed `ContextScope` actually did).

Now we have a `Diagnoser`: code in `check` that can better explain the
problem than shared logic it is calling into passes a callback that
builds a caller-specific diagnostic. The callee then can attach relevant
labels and emit it. Diagnostics no longer store `contexts` and consumers
no longer need the logic to restructure things. We move all (but two) of
the old contexts to be normal messages emitted in this way, and we move
some diagnostics to become labels. Each of the new normal messages
corresponds to a new diagnostic kind as usual. Common code following
this pattern now _requires_ the `Diagnoser` to be passed (or emit
nothing), and this uncovered three places where an empty context was
used that made the rendered form miss key information. All three are
fixed with new diagnostics, one already covered by tests, and two with
TODOs to add test coverage.

We also completely remove the old `ContextScope` and
`CARBON_DIAGNOSTIC_CONTEXT` and rename `AnnotationScope` to
`ContextScope`. It is only used to attach information about when/where a
diagnostic occurred.

Labels also no longer have categories. What were `Primary` are now
`ExtraRange`s on the diagnostic rather than labels. Labels are now
always informational.

`DeclaredName` now narrows the range of a label when the range is a
declaration of a named entity to only be the range of that name. For
entities that don't have a declared name, the entire declaration remains
the range. The code building and emitting these diagnostics can skip
them if the declared location isn't distinct from the diagnostic
location.

Wording is largely unchanged here so we can just review the _structural_
change. #7991 iterates using this to improve locations and adds missing
labels. A subsequent PR will iterate on the wording to increasingly fit
within this structural model.

This is separated out as a way to review incrementally, and so that
subsequently we don't have to review wording improvements that only make
sense in a new structure that you cannot see yet. It seems easier to
look at the structure here even with awkward wording.

Assisted-by: Claude Code
2026-11-22 05:19:35 +00:00

326 lines
12 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 "toolchain/language_server/context.h"
#include <algorithm>
#include <memory>
#include <optional>
#include <utility>
#include "common/check.h"
#include "common/raw_string_ostream.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/TargetParser/Host.h"
#include "toolchain/base/clang_invocation.h"
#include "toolchain/base/shared_value_stores.h"
#include "toolchain/check/check.h"
#include "toolchain/diagnostics/consumer.h"
#include "toolchain/diagnostics/diagnostic.h"
#include "toolchain/diagnostics/emitter.h"
#include "toolchain/diagnostics/stream_consumer.h"
#include "toolchain/driver/compile_driver.h"
#include "toolchain/driver/compile_options.h"
#include "toolchain/lex/lex.h"
#include "toolchain/lex/tokenized_buffer.h"
#include "toolchain/parse/parse.h"
#include "toolchain/parse/tree_and_subtrees.h"
namespace Carbon::LanguageServer {
namespace {
// A consumer for turning diagnostics into a `textDocument/publishDiagnostics`
// notification.
// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_publishDiagnostics
class DiagnosticConsumer : public Diagnostics::Consumer {
public:
// Initializes params with the target file information.
explicit DiagnosticConsumer(Context* context,
const clang::clangd::URIForFile& uri,
std::optional<int64_t> version)
: context_(context), params_{.uri = uri, .version = version} {}
// Turns a diagnostic into an LSP diagnostic.
auto HandleDiagnostic(Diagnostics::Diagnostic diagnostic) -> void override {
const Diagnostics::Loc& loc = diagnostic.message.loc;
if (loc.filename != params_.uri.file()) {
// `pushDiagnostic` requires diagnostics to be associated with a location
// in the current file. Suppress diagnostics rooted in other files.
// TODO: Consider if there's a better way to handle this.
RawStringOstream stream;
Diagnostics::StreamConsumer consumer(&stream);
consumer.HandleDiagnostic(diagnostic);
CARBON_DIAGNOSTIC(LanguageServerDiagnosticInWrongFile, Warning,
"dropping diagnostic in {0}:\n{1}", std::string,
std::string);
context_->file_emitter().Emit(params_.uri.file(),
LanguageServerDiagnosticInWrongFile,
loc.filename.str(), stream.TakeStr());
return;
}
// Add the main message.
params_.diagnostics.push_back(clang::clangd::Diagnostic{
.range = GetRange(loc),
.severity = GetSeverity(diagnostic.level),
.source = "carbon",
.message = diagnostic.message.Format(),
});
// TODO: Figure out constructing URIs for the locations of labels.
}
// Returns the constructed request.
auto params() -> const clang::clangd::PublishDiagnosticsParams& {
return params_;
}
private:
// Returns the LSP range for a diagnostic. Note that Carbon uses 1-based
// numbers while LSP uses 0-based.
//
// A location may have no line number (for example, a diagnostic about the
// file as a whole) or no column number. LSP has no way to express either, and
// clients reject negative positions, so point at the start of the file or
// line instead.
auto GetRange(const Diagnostics::Loc& loc) -> clang::clangd::Range {
if (loc.line_number <= 0) {
return {.start = {.line = 0, .character = 0},
.end = {.line = 0, .character = 0}};
}
int line = loc.line_number - 1;
if (loc.column_number <= 0) {
return {.start = {.line = line, .character = 0},
.end = {.line = line, .character = 0}};
}
int start_character = loc.column_number - 1;
return {.start = {.line = line, .character = start_character},
.end = {.line = line,
.character = start_character + std::max(loc.length, 0)}};
}
// Converts a diagnostic level to an LSP severity.
auto GetSeverity(Diagnostics::Level level) -> int {
// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnosticSeverity
enum class DiagnosticSeverity {
Error = 1,
Warning = 2,
Information = 3,
Hint = 4,
};
switch (level) {
case Diagnostics::Level::Error:
return static_cast<int>(DiagnosticSeverity::Error);
case Diagnostics::Level::Warning:
return static_cast<int>(DiagnosticSeverity::Warning);
}
}
Context* context_;
clang::clangd::PublishDiagnosticsParams params_;
};
// A virtual file corresponding to a file that has been opened and potentially
// edited by the language client.
class VirtualFile : public llvm::vfs::File {
public:
explicit VirtualFile(const Context::File* file) : file_(file) {}
auto status() -> llvm::ErrorOr<llvm::vfs::Status> override {
return llvm::vfs::Status(
file_->filename(), llvm::sys::fs::UniqueID(0, 0),
std::chrono::system_clock::now(), 0, 0, file_->text().size(),
llvm::sys::fs::file_type::regular_file, llvm::sys::fs::all_all);
}
auto getBuffer(const llvm::Twine& /*name*/, int64_t /*file_size*/,
bool /*requires_null_terminator*/, bool /*is_volatile*/)
-> llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> override {
return llvm::MemoryBuffer::getMemBuffer(file_->text(), file_->filename());
}
auto close() -> std::error_code override { return std::error_code(); }
private:
const Context::File* file_;
};
// A virtual file system containing the documents whose contents were customized
// by the language client. We can't use InMemoryFileSystem for this, because it
// only supports setting the contents for each file once.
//
// TODO: Investigate whether we can replace this with clangd's `DraftStore`.
class VirtualFileSystem : public llvm::vfs::FileSystem {
public:
explicit VirtualFileSystem(Context* context) : context_(context) {}
auto status(const llvm::Twine& path)
-> llvm::ErrorOr<llvm::vfs::Status> override {
std::string path_str = path.str();
if (auto lookup_result = context_->files().Lookup(path_str)) {
return llvm::vfs::Status(path_str, llvm::sys::fs::UniqueID(0, 0),
std::chrono::system_clock::now(), /*User=*/0,
/*Group=*/0, lookup_result.value().text().size(),
llvm::sys::fs::file_type::regular_file,
llvm::sys::fs::all_all);
}
return std::make_error_code(std::errc::no_such_file_or_directory);
}
auto openFileForRead(const llvm::Twine& path)
-> llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> override {
std::string path_str = path.str();
if (auto lookup_result = context_->files().Lookup(path_str)) {
return std::unique_ptr<llvm::vfs::File>(
new VirtualFile(&lookup_result.value()));
}
return std::make_error_code(std::errc::no_such_file_or_directory);
}
auto dir_begin(const llvm::Twine& /*dir*/, std::error_code& ec)
-> llvm::vfs::directory_iterator override {
ec = std::make_error_code(std::errc::no_such_file_or_directory);
return llvm::vfs::directory_iterator();
}
auto getCurrentWorkingDirectory() const
-> llvm::ErrorOr<std::string> override {
return std::string("");
}
auto setCurrentWorkingDirectory(const llvm::Twine& /*path*/)
-> std::error_code override {
return std::error_code();
}
private:
Context* context_;
};
} // namespace
Context::Context(const InstallPaths* installation,
llvm::raw_ostream* vlog_stream,
Diagnostics::Consumer* consumer,
clang::clangd::LSPBinder::RawOutgoing* outgoing,
bool prelude_import)
: installation_(installation),
vlog_stream_(vlog_stream),
file_emitter_(consumer),
no_loc_emitter_(consumer),
outgoing_(outgoing),
prelude_import_(prelude_import) {
auto ls_fs = llvm::makeIntrusiveRefCnt<VirtualFileSystem>(this);
auto vfs = llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
llvm::vfs::getRealFileSystem());
vfs->pushOverlay(ls_fs);
vfs_ = vfs;
}
auto Context::File::sem_ir_index() const -> const SemIRIndex* {
if (!sem_ir_index_) {
const auto* sem_ir = this->sem_ir();
if (!sem_ir) {
return nullptr;
}
sem_ir_index_.emplace(*sem_ir, tree_and_subtrees());
}
return &*sem_ir_index_;
}
auto Context::File::sem_ir_text() const -> const SemIRText* {
if (!is_test_file_) {
return nullptr;
}
if (!sem_ir_text_) {
sem_ir_text_.emplace(text_);
}
return sem_ir_text_->empty() ? nullptr : &*sem_ir_text_;
}
auto Context::File::SetText(Context& context, std::optional<int64_t> version,
llvm::StringRef text) -> void {
// Clear state dependent on the source text.
compile_driver_.reset();
sem_ir_index_.reset();
sem_ir_text_.reset();
text_ = text.str();
is_test_file_ = language_id_ == "carbon-testdata";
// A consumer to gather diagnostics for the file.
DiagnosticConsumer consumer(&context, uri_, version);
if (is_test_file_) {
// A test file isn't a Carbon source file: it holds any number of input
// files, plus the output expected from compiling them. Compiling it as one
// source file would report errors on almost every line, so don't. Publish
// the empty diagnostic list anyway, to clear anything left over from
// before the file became a test file.
// TODO: Compile each of the file's splits separately, so that the Carbon
// source in a test file gets the same support as any other Carbon source.
context.PublishDiagnostics(consumer.params());
return;
}
// TODO: Make the processing asynchronous, to better handle rapid text
// updates.
llvm::raw_null_ostream null_stream;
DriverEnv driver_env(context.vfs(), &context.installation(),
/*input_stream=*/nullptr, &null_stream, &null_stream,
/*fuzzing=*/false,
/*enable_leaking=*/false, &consumer);
// TODO: Either use `raw_pwrite_stream` for all vlog streams or stop requiring
// one in DriverEnv.
driver_env.vlog_stream =
static_cast<llvm::raw_pwrite_stream*>(context.vlog_stream());
codegen_options_ = CodegenOptions();
options_ = CompileOptions(&codegen_options_);
codegen_options_.target = codegen_options_.host;
options_.phase = CompileOptions::Phase::Check;
options_.prelude_import = context.prelude_import();
options_.input_filenames.push_back(filename());
options_.FixupFlags();
compile_driver_ = std::make_unique<CompileDriver>(&options_);
auto map_input = [](llvm::StringRef) -> std::string { return ""; };
if (!compile_driver_->Initialize(driver_env, map_input)) {
context.PublishDiagnostics(consumer.params());
return;
}
if (!compile_driver_->Compile(driver_env).success) {
context.PublishDiagnostics(consumer.params());
return;
}
// Note we need to publish diagnostics even when empty.
// TODO: Consider caching previously published diagnostics and only publishing
// when they change.
context.PublishDiagnostics(consumer.params());
}
auto Context::LookupFile(llvm::StringRef filename) -> File* {
if (!filename.ends_with(".carbon")) {
CARBON_DIAGNOSTIC(LanguageServerFileUnsupported, Warning,
"non-Carbon file requested");
file_emitter_.Emit(filename, LanguageServerFileUnsupported);
return nullptr;
}
if (auto lookup_result = files().Lookup(filename)) {
return &lookup_result.value();
} else {
CARBON_DIAGNOSTIC(LanguageServerFileUnknown, Warning,
"unknown file requested");
file_emitter_.Emit(filename, LanguageServerFileUnknown);
return nullptr;
}
}
} // namespace Carbon::LanguageServer