context.cpp 7.0 KB

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