context.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/language_server/context.h"
  5. #include <memory>
  6. #include "common/check.h"
  7. #include "common/raw_string_ostream.h"
  8. #include "toolchain/base/shared_value_stores.h"
  9. #include "toolchain/check/check.h"
  10. #include "toolchain/diagnostics/diagnostic.h"
  11. #include "toolchain/diagnostics/diagnostic_consumer.h"
  12. #include "toolchain/lex/lex.h"
  13. #include "toolchain/lex/tokenized_buffer.h"
  14. #include "toolchain/parse/parse.h"
  15. #include "toolchain/parse/tree_and_subtrees.h"
  16. namespace Carbon::LanguageServer {
  17. namespace {
  18. // A consumer for turning diagnostics into a `textDocument/publishDiagnostics`
  19. // notification.
  20. // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_publishDiagnostics
  21. class DiagnosticConsumer : public Diagnostics::Consumer {
  22. public:
  23. // Initializes params with the target file information.
  24. explicit DiagnosticConsumer(Context* context,
  25. const clang::clangd::URIForFile& uri,
  26. std::optional<int64_t> version)
  27. : context_(context), params_{.uri = uri, .version = version} {}
  28. // Turns a diagnostic into an LSP diagnostic.
  29. auto HandleDiagnostic(Diagnostics::Diagnostic diagnostic) -> void override {
  30. const auto& message = diagnostic.messages[0];
  31. if (message.loc.filename != params_.uri.file()) {
  32. // `pushDiagnostic` requires diagnostics to be associated with a location
  33. // in the current file. Suppress diagnostics rooted in other files.
  34. // TODO: Consider if there's a better way to handle this.
  35. RawStringOstream stream;
  36. Diagnostics::StreamConsumer consumer(&stream);
  37. consumer.HandleDiagnostic(diagnostic);
  38. CARBON_DIAGNOSTIC(LanguageServerDiagnosticInWrongFile, Warning,
  39. "dropping diagnostic in {0}:\n{1}", std::string,
  40. std::string);
  41. context_->file_emitter().Emit(
  42. params_.uri.file(), LanguageServerDiagnosticInWrongFile,
  43. message.loc.filename.str(), stream.TakeStr());
  44. return;
  45. }
  46. // Add the main message.
  47. params_.diagnostics.push_back(clang::clangd::Diagnostic{
  48. .range = GetRange(message.loc),
  49. .severity = GetSeverity(diagnostic.level),
  50. .source = "carbon",
  51. .message = message.Format(),
  52. });
  53. // TODO: Figure out constructing URIs for note locations.
  54. }
  55. // Returns the constructed request.
  56. auto params() -> const clang::clangd::PublishDiagnosticsParams& {
  57. return params_;
  58. }
  59. private:
  60. // Returns the LSP range for a diagnostic. Note that Carbon uses 1-based
  61. // numbers while LSP uses 0-based.
  62. auto GetRange(const Diagnostics::Loc& loc) -> clang::clangd::Range {
  63. return {.start = {.line = loc.line_number - 1,
  64. .character = loc.column_number - 1},
  65. .end = {.line = loc.line_number,
  66. .character = loc.column_number + loc.length}};
  67. }
  68. // Converts a diagnostic level to an LSP severity.
  69. auto GetSeverity(Diagnostics::Level level) -> int {
  70. // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnosticSeverity
  71. enum class DiagnosticSeverity {
  72. Error = 1,
  73. Warning = 2,
  74. Information = 3,
  75. Hint = 4,
  76. };
  77. switch (level) {
  78. case Diagnostics::Level::Error:
  79. return static_cast<int>(DiagnosticSeverity::Error);
  80. case Diagnostics::Level::Warning:
  81. return static_cast<int>(DiagnosticSeverity::Warning);
  82. default:
  83. CARBON_FATAL("Unexpected diagnostic level: {0}", level);
  84. }
  85. }
  86. Context* context_;
  87. clang::clangd::PublishDiagnosticsParams params_;
  88. };
  89. } // namespace
  90. auto Context::File::SetText(Context& context, std::optional<int64_t> version,
  91. llvm::StringRef text) -> void {
  92. // Clear state dependent on the source text.
  93. tree_and_subtrees_.reset();
  94. tree_.reset();
  95. tokens_.reset();
  96. value_stores_.reset();
  97. source_.reset();
  98. // A consumer to gather diagnostics for the file.
  99. DiagnosticConsumer consumer(&context, uri_, version);
  100. // TODO: Make the processing asynchronous, to better handle rapid text
  101. // updates.
  102. CARBON_CHECK(!source_ && !value_stores_ && !tokens_ && !tree_,
  103. "We currently cache everything together");
  104. // TODO: Diagnostics should be passed to the LSP instead of dropped.
  105. std::optional source =
  106. SourceBuffer::MakeFromStringCopy(uri_.file(), text, consumer);
  107. if (!source) {
  108. // Failing here should be rare, but provide stub data for recovery so that
  109. // we can have a simple API.
  110. source = SourceBuffer::MakeFromStringCopy(uri_.file(), "", consumer);
  111. CARBON_CHECK(source, "Making an empty buffer should always succeed");
  112. }
  113. source_ = std::make_unique<SourceBuffer>(std::move(*source));
  114. value_stores_ = std::make_unique<SharedValueStores>();
  115. tokens_ = std::make_unique<Lex::TokenizedBuffer>(
  116. Lex::Lex(*value_stores_, *source_, consumer));
  117. tree_ = std::make_unique<Parse::Tree>(
  118. Parse::Parse(*tokens_, consumer, context.vlog_stream()));
  119. tree_and_subtrees_ =
  120. std::make_unique<Parse::TreeAndSubtrees>(*tokens_, *tree_);
  121. SemIR::File sem_ir(tree_.get(), SemIR::CheckIRId(0), tree_->packaging_decl(),
  122. *value_stores_, uri_.file().str());
  123. auto getter = [this]() -> const Parse::TreeAndSubtrees& {
  124. return *tree_and_subtrees_;
  125. };
  126. // TODO: Support cross-file checking when multiple files have edits.
  127. llvm::SmallVector<Check::Unit> units = {{.consumer = &consumer,
  128. .value_stores = value_stores_.get(),
  129. .timings = nullptr,
  130. .tree_and_subtrees_getter = getter,
  131. .sem_ir = &sem_ir}};
  132. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> fs =
  133. new llvm::vfs::InMemoryFileSystem;
  134. // TODO: Include the prelude.
  135. Check::CheckParseTrees(units, /*prelude_import=*/false, fs,
  136. context.vlog_stream(), /*fuzzing=*/false);
  137. // Note we need to publish diagnostics even when empty.
  138. // TODO: Consider caching previously published diagnostics and only publishing
  139. // when they change.
  140. context.PublishDiagnostics(consumer.params());
  141. }
  142. auto Context::LookupFile(llvm::StringRef filename) -> File* {
  143. if (!filename.ends_with(".carbon")) {
  144. CARBON_DIAGNOSTIC(LanguageServerFileUnsupported, Warning,
  145. "non-Carbon file requested");
  146. file_emitter_.Emit(filename, LanguageServerFileUnsupported);
  147. return nullptr;
  148. }
  149. if (auto lookup_result = files().Lookup(filename)) {
  150. return &lookup_result.value();
  151. } else {
  152. CARBON_DIAGNOSTIC(LanguageServerFileUnknown, Warning,
  153. "unknown file requested");
  154. file_emitter_.Emit(filename, LanguageServerFileUnknown);
  155. return nullptr;
  156. }
  157. }
  158. } // namespace Carbon::LanguageServer