language_server.cpp 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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 "language_server/language_server.h"
  5. #include "clang-tools-extra/clangd/Protocol.h"
  6. #include "toolchain/base/value_store.h"
  7. #include "toolchain/diagnostics/null_diagnostics.h"
  8. #include "toolchain/lex/lex.h"
  9. #include "toolchain/parse/node_kind.h"
  10. #include "toolchain/parse/parse.h"
  11. #include "toolchain/source/source_buffer.h"
  12. namespace Carbon::LS {
  13. void LanguageServer::OnDidOpenTextDocument(
  14. clang::clangd::DidOpenTextDocumentParams const& params) {
  15. files_.emplace(params.textDocument.uri.file(), params.textDocument.text);
  16. }
  17. void LanguageServer::OnDidChangeTextDocument(
  18. clang::clangd::DidChangeTextDocumentParams const& params) {
  19. // full text is sent if full sync is specified in capabilities.
  20. assert(params.contentChanges.size() == 1);
  21. std::string file = params.textDocument.uri.file().str();
  22. files_[file] = params.contentChanges[0].text;
  23. }
  24. void LanguageServer::OnInitialize(
  25. clang::clangd::NoParams const& /*client_capabilities*/,
  26. clang::clangd::Callback<llvm::json::Object> cb) {
  27. llvm::json::Object capabilities{{"documentSymbolProvider", true},
  28. {"textDocumentSync", /*Full=*/1}};
  29. llvm::json::Object reply{{"capabilities", std::move(capabilities)}};
  30. cb(reply);
  31. };
  32. auto LanguageServer::onNotify(llvm::StringRef method, llvm::json::Value value)
  33. -> bool {
  34. if (method == "exit") {
  35. return false;
  36. }
  37. if (auto handler = handlers_.NotificationHandlers.find(method);
  38. handler != handlers_.NotificationHandlers.end()) {
  39. handler->second(std::move(value));
  40. } else {
  41. clang::clangd::log("unhandled notification {0}", method);
  42. }
  43. return true;
  44. }
  45. auto LanguageServer::onCall(llvm::StringRef method, llvm::json::Value params,
  46. llvm::json::Value id) -> bool {
  47. if (auto handler = handlers_.MethodHandlers.find(method);
  48. handler != handlers_.MethodHandlers.end()) {
  49. // TODO: improve this if add threads
  50. handler->second(std::move(params),
  51. [&](llvm::Expected<llvm::json::Value> reply) {
  52. transport_->reply(id, std::move(reply));
  53. });
  54. } else {
  55. transport_->reply(
  56. id, llvm::make_error<clang::clangd::LSPError>(
  57. "method not found", clang::clangd::ErrorCode::MethodNotFound));
  58. }
  59. return true;
  60. }
  61. auto LanguageServer::onReply(llvm::json::Value /*id*/,
  62. llvm::Expected<llvm::json::Value> /*result*/)
  63. -> bool {
  64. return true;
  65. }
  66. // Returns the text of first child of kind Parse::NodeKind::IdentifierName.
  67. static auto GetIdentifierName(const SharedValueStores& value_stores,
  68. const Lex::TokenizedBuffer& tokens,
  69. const Parse::Tree& p, Parse::NodeId node)
  70. -> std::optional<llvm::StringRef> {
  71. for (auto ch : p.children(node)) {
  72. if (p.node_kind(ch) == Parse::NodeKind::IdentifierName) {
  73. return value_stores.identifiers().Get(
  74. tokens.GetIdentifier(p.node_token(ch)));
  75. }
  76. }
  77. return std::nullopt;
  78. }
  79. void LanguageServer::OnDocumentSymbol(
  80. clang::clangd::DocumentSymbolParams const& params,
  81. clang::clangd::Callback<std::vector<clang::clangd::DocumentSymbol>> cb) {
  82. SharedValueStores value_stores;
  83. llvm::vfs::InMemoryFileSystem vfs;
  84. auto file = params.textDocument.uri.file().str();
  85. vfs.addFile(file, /*mtime=*/0,
  86. llvm::MemoryBuffer::getMemBufferCopy(files_.at(file)));
  87. auto buf = SourceBuffer::CreateFromFile(vfs, file, NullDiagnosticConsumer());
  88. auto lexed = Lex::Lex(value_stores, *buf, NullDiagnosticConsumer());
  89. auto parsed = Parse::Parse(lexed, NullDiagnosticConsumer(), nullptr);
  90. std::vector<clang::clangd::DocumentSymbol> result;
  91. for (const auto& node : parsed.postorder()) {
  92. clang::clangd::SymbolKind symbol_kind;
  93. switch (parsed.node_kind(node)) {
  94. case Parse::NodeKind::FunctionDecl:
  95. case Parse::NodeKind::FunctionDefinitionStart:
  96. symbol_kind = clang::clangd::SymbolKind::Function;
  97. break;
  98. case Parse::NodeKind::Namespace:
  99. symbol_kind = clang::clangd::SymbolKind::Namespace;
  100. break;
  101. case Parse::NodeKind::InterfaceDefinitionStart:
  102. case Parse::NodeKind::NamedConstraintDefinitionStart:
  103. symbol_kind = clang::clangd::SymbolKind::Interface;
  104. break;
  105. case Parse::NodeKind::ClassDefinitionStart:
  106. symbol_kind = clang::clangd::SymbolKind::Class;
  107. break;
  108. default:
  109. continue;
  110. }
  111. if (auto name = GetIdentifierName(value_stores, lexed, parsed, node)) {
  112. auto tok = parsed.node_token(node);
  113. clang::clangd::Position pos{lexed.GetLineNumber(tok) - 1,
  114. lexed.GetColumnNumber(tok) - 1};
  115. clang::clangd::DocumentSymbol symbol{
  116. .name = std::string(*name),
  117. .kind = symbol_kind,
  118. .range = {.start = pos, .end = pos},
  119. .selectionRange = {.start = pos, .end = pos},
  120. };
  121. result.push_back(symbol);
  122. }
  123. }
  124. cb(result);
  125. }
  126. void LanguageServer::Start() {
  127. auto transport =
  128. clang::clangd::newJSONTransport(stdin, llvm::outs(), nullptr, true);
  129. LanguageServer ls(std::move(transport));
  130. clang::clangd::LSPBinder binder(ls.handlers_, ls);
  131. binder.notification("textDocument/didOpen", &ls,
  132. &LanguageServer::OnDidOpenTextDocument);
  133. binder.notification("textDocument/didChange", &ls,
  134. &LanguageServer::OnDidChangeTextDocument);
  135. binder.method("initialize", &ls, &LanguageServer::OnInitialize);
  136. binder.method("textDocument/documentSymbol", &ls,
  137. &LanguageServer::OnDocumentSymbol);
  138. auto error = ls.transport_->loop(ls);
  139. llvm::errs() << "Error: " << error << "\n";
  140. }
  141. } // namespace Carbon::LS