context.cpp 6.9 KB

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