context.cpp 7.4 KB

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