language_server.cpp 6.1 KB

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